简体   繁体   中英

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

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM