What is the correct syntax to render an HTML img tag in ASP.NET MVC 2?
<img alt="Upload Profile Pic" src="<%= ViewData["PicSource"].ToString() %>" />
UPDATE:
Also, when we write this syntax, visual studio underlines several elements of our html code with curly red lines just like when we have some syntax errors and it looks like that the syntax we have written wil开发者_开发技巧l not work and is wrong, but actually when I built it, it worked.
It also denies to auto format the html code. This was an enough good reason for me for asking this question because even though I knew that this syntax will work, still then when everytime I write like this, I feel that I have done something wrong.
Yes, you can write like that.
However, it is often referred to as "spaghetti code", and the best practice would be to use a helper method.
public static class ImageHelper
{
public static MvcHtmlString Image(this HtmlHelper html, string sourcePath, object htmlAttributes)
{
return html.Image(sourcePath, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString Image(this HtmlHelper html, string sourcePath, IDictionary<string,object> htnlAttributes)
{
if(string.IsNullOrEmpty(sourcePath))
{
throw new ArgumentException("Image source path cannot be null or empty.", "sourcePath");
}
TagBuilder tagBuilder = new TagBuilder("img");
tagBuilder.MergeAttributes<string,object>(htnlAttributes);
tagBuilder.MergeAttribute("src", sourcePath, true);
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));
}
}
then, you're use looks like
Html.Image(ViewData["PicSource"] as string, new {alt = "Upload Profile Pic"});
精彩评论