ridermansb
ridermansb

Reputation: 11059

How to create my custom helper in asp.net MVC?

I asked this question here on the forum for static link helper, but I got no answers yet. So I decided to create my own helper.

I'm trying to create a helper for a static link

<a href='xx'>yy</a>

but is displaying the HTML code.

Using:

<div>
@Html.Link("www.google.com", "Google")
</div>

Result:

<a href="www.google.com">Google</a> 

See my class:

public static class BindHelper
{
    public static TagBuilder Link(this HtmlHelper helper, string targetUrl, string text)
    {
        TagBuilder imglink = new TagBuilder("a");
        imglink.MergeAttribute("href", targetUrl);
        imglink.InnerHtml = text;
        return imglink;
    }
}

How to create my own helper? Already researched on several sites and some extended the method returns a string in the other class TagBuilder but both ways it displays the HTML code on page

Upvotes: 0

Views: 905

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190943

Return an MvcHtmlString. That is what MVC does internally. It (somewhat) implements IHtmlString which tells the HTML encoder not to reencode the value.

Also add your namespace to the build configuration section of the web.config.

Upvotes: 4

Related Questions