自定义html帮助器中的css id

时间:2014-07-21 11:09:05

标签: c# css asp.net-mvc razor

我有自定义的html助手,想在那里添加css id标签。 这是我的自定义html助手:

 public static class CustomHtmlHelpers
{
    public static IHtmlString Image(this HtmlHelper helper, string src)
    {
        TagBuilder tb = new TagBuilder("img");
        tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
        return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
    }
}

这是我在razor视图中的代码:

<div class="display-label">
   @Html.DisplayNameFor(model => model.Photo)
</div>
<div class="display-field">
   @Html.Image(@Model.Photo)
</div>

我试过了

@Html.Image(@Model.Photo, new { @id = "myId" })

但它不起作用

2 个答案:

答案 0 :(得分:2)

您可以尝试将HTML帮助器更改为:

public static IHtmlString Image(this HtmlHelper helper, object htmlAttributes)

并添加代码:

tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));

链接: http://www.asp.net/mvc/tutorials/older-versions/views/using-the-tagbuilder-class-to-build-html-helpers-cs

答案 1 :(得分:2)

public static class CustomHtmlHelpers
{
    public static IHtmlString Image(this HtmlHelper helper, 
        string src, 
        object htmlAttributes)
    {
        TagBuilder tb = new TagBuilder("img");
        tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
        tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
    }
}

和html

@Html.Image(@Model.Photo, new { @id = "myId" })