Thursday, September 24, 2015

Custom HTML Helpers- Extend ActionLink

Requirement: Create custom container DIV control that takes in HTML markup as input.

Assuming you already have an MVC website created.

Step 1: Create a folder named "Helpers" in the root of your MVC website.

Step 2: Create a static class named "HtmlHelper" under the newly created folder.

Step 3: Use following Namespaces:

using System;
using System.Text;
using System.Web;
using System.Web.Mvc;

Step 4: Create a static function as follows:

public static IHtmlString CustomActionLink(this HtmlHelper helper, string Id, string caption, string action, string controller, string tooltip, Dictionary<string, object> htmlAttributes = null)
        {
            //If htmlAttributes is null, create an instance
            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary<string, object>();
            }

            //Add properties
            htmlAttributes.Add("title", tooltip);
            htmlAttributes.Add("class", "InformActionLink");

            //Finally return the custom ActionLink
            return helper.ActionLink(caption, action, controller, null, htmlAttributes);
        }

Step 5: Compile the project.

Step 6: Open the view in which you want to render the above control.

Step 7: Add reference to the newly created control on top of your view:

@using <Your ProjectName>.<FolderName>
Example @using HtmlHelpers.Helpers

Step 8: Add following markup:

@Html.CustomActionLink("lnkAddNew", "Add New", "ClientActionName", "ClientControllerName", "Add New Client")
OR
@Html.CustomActionLink("lnkAddNew", "Add New", "ClientActionName", "ClientControllerName", "Add New Client", null)
OR
@Html.CustomActionLink("lnkAddNew", "Add New", "ClientActionName", "ClientControllerName", "Add New Client", new Dictionary<string, object>() {{ "onclick" , "alert('testing')"}})

No comments:

Post a Comment