Writing a Custom Html Helper for Button in ASP.NET Razor

Yasser Shaikh
Dec 20, 2014 · 1 min read

Html Helpers are used when we want to have a custom html with/without some logic repeated across your application. Today I wanted to have all the buttons shown across the application behave in a particular way depending upon the logged in user, this can easily be done using HtmlHelper.

Code

public static class CustomHtmlHelpers
{
public static MvcHtmlString CustomButton(this HtmlHelper htmlHelper, string innerHtml, IDictionary<string, string> htmlAttributes)
{
var builder = new TagBuilder("a") {InnerHtml = innerHtml};
builder.MergeAttributes(htmlAttributes);
return MvcHtmlString.Create(builder.ToString());
}
}

In the IDictionary<string, string> htmlAttributes parameter you can pass all the html attributes you need your button to have, for example: class, href, or any other html attribute for that matter.

Example

@Html.CustomButton("<i class='fa fa-plus'></i>&nbsp; Create Something", new Dictionary<string, string> { { "class", "btn btn-primary" }, { "href", "#create" } })

You might wanna read another related article on Html Helpers.

Yasser Shaikh's blog

It's supposed to be automatic, but actually you have to push this button.

Yasser Shaikh

Written by

Yasser Shaikh's blog

It's supposed to be automatic, but actually you have to push this button.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade