I have my custom html helper and want to add css id tag there. this is my custom html helper:
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));
}
}
and here's my code in razor view:
<div class="display-label">
@Html.DisplayNameFor(model => model.Photo)
</div>
<div class="display-field">
@Html.Image(@Model.Photo)
</div>
I have tried
@Html.Image(@Model.Photo, new { @id = "myId" })
but it doesn't works
Can you try change your HTML helper to this:
public static IHtmlString Image(this HtmlHelper helper, object htmlAttributes)
and add code:
tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));
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));
}
}
and html
@Html.Image(@Model.Photo, new { @id = "myId" })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.