我有自定义的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" })
但它不起作用
答案 0 :(得分:2)
您可以尝试将HTML帮助器更改为:
public static IHtmlString Image(this HtmlHelper helper, object htmlAttributes)
并添加代码:
tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));
答案 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" })