是的,你可以这样写。
但是,它通常被称为“意大利面条代码”,最佳实践是使用辅助方法。
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));
}
}
那么,你的使用看起来像
Html.Image(ViewData["PicSource"] as string, new {alt = "Upload Profile Pic"});