How to create html helper in razor (.NET MVC)

Razor is an ASP.NET programming syntax used to create dynamic web pages with the C# or Visual Basic .NET programming languages. The Razor syntax is a template markup syntax, based on the C# programming language, that enables the programmer to use an HTML construction workflow[clarification needed]. Instead of using the ASP.NET.ASPX markup syntax with <%= %> symbols to indicate code blocks, Razor syntax starts code blocks with a @ character and does not require explicit closing of the code-block.

HTML Helper

Html helper is much like control that returns HTML string. But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
In this post, I will show you how to create Html helper in MVC.NET.There are two ways to create an HTML helper in MVC.

Inline Helpers

These are created in the same view by using the Razor @helper tag. These helpers can be reused only on the same view. For example in the following code snippet, I have created a ToUpper HTML helper that wraps the text inside the b tag and converts the text to upper case

@helper ToUpper(string text) { 
    ViewBag.Title = "Demo";
    Layout = null;

Custom Helper

If you want to use your Html helper at the application level then you can create a custom helper.
You can create a custom helper function by creating the extensions method. In the following code snippet, I have created a SubmitButton HTML helper that generates submit button.

public static class HtmlHelpers
        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string text)
            string str = "<input type=\"submit\" value=\"" + text + "\" />";
            return new MvcHtmlString(str);

How to use custom Helper

Next Post Previous Post
No Comment
Add Comment
comment url