Pages

How To Create Custom Html Helper In MVC

Saturday, 8 November 2014
A Html helper just a method which returns a string having string or plain text, which can be used in our view . We have In-built html helper like Html.ActionLink(), Html.TextBox().

In this article we will try to understand , How to create own custom html helper in MVC.
Let's create a new mvc application.

Step 1 - Create a new mvc application , name as "CustomHelperDemo".

Step 2 - Add a new class post to model folder.

public class Post
    {
       public virtual int Id{ get; set; }
        public virtual string Title{ get; set; }
        public virtual DateTime PostedOn{ get; set; }
        public virtual string Category  {get;set;}
    }

Step 3 - Add a new class ActionLinkHelpers to create custom HTML helper using extension method.

public static class ActionLinkHelpers
{
 public static MvcHtmlString PostsLink(this HtmlHelper htmlHelper, Post post)
        {
            return htmlHelper.ActionLink(post.Title, "Blog", "Home",
                new
                {
                    year = post.PostedOn.Year,
                    month = post.PostedOn.Month,
                    category = post.Category
                },
                new
                {
                    Title = post.Title,
                    Id = post.Id
                });
        }
    }
Step 4 - Build the project, and include below code in view where do you want to use your custom class.

@using CustomHelperDemo

But if you want to use across all over the view without inckuding "@using CustomHelperDemo" then you have to add namespace in View's Web.config

<add namespace="CustomHelperDemo"/>

And now you can use your own custom html helper in your view.
@model CustomHelperDemo.Post

@Html.PostsLink(Model)

No comments:

Post a Comment