gsiradze
gsiradze

Reputation: 4733

css id in custom html helper

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

Upvotes: 0

Views: 868

Answers (2)

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

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" })

Upvotes: 2

freshbm
freshbm

Reputation: 5622

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));

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

Upvotes: 2

Related Questions