1
<img alt="Upload Profile Pic" src="<%= ViewData["PicSource"].ToString() %>" />

UPDATE:此外,当我们编写此语法时,Visual Studio 会在我们的 html 代码的几个元素下划线,就像我们有一些语法错误时一样,看起来我们编写的语法不起作用并且是错误的,但实际上当我建造它,它工作。

它还拒绝自动格式化 html 代码。这是我提出这个问题的充分理由,因为即使我知道这种语法会起作用,但每次我这样写时,我都觉得我做错了什么。

4

1 回答 1

3

是的,你可以这样写。

但是,它通常被称为“意大利面条代码”,最佳实践是使用辅助方法。

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"});
于 2011-03-12T12:29:42.657 回答