Thursday, September 24, 2015

Custom HTML Helpers- Link

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 CustomLink(this HtmlHelper helper, string Id, string caption, string tooltip, Dictionary<string, object> htmlAttributes = null)
        {
            var attributes = new StringBuilder();

            //Read HTML Attributes and construct string out of it
            if (htmlAttributes != null)
            {
                foreach (var attr in htmlAttributes.ToArray())
                {
                    attributes.Append($"{attr.Key.ToString()}=\"{attr.Value.ToString()}\"");
                }

            }
            else
            {
                htmlAttributes = new Dictionary<string, object>();
            }

            var sb = new StringBuilder();

            //Construct final control with markup and htmlAttributes
            sb.Append($"<a id='{Id}' class='InformActionLink' {attributes} title='{tooltip}'>{caption}</a>");

            //Return as HTML String
            return new HtmlString(sb.ToString());

        }

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.CustomLink ("lnkAddNew", "Add", "Add New Client", new Dictionary<string, object>() { { "onclick" , "alert('testing')"} })
OR
@Html.CustomLink ("lnkAddNew", "Add", "Add New Client", null)
OR
@Html.CustomLink ("lnkAddNew", "Add", "Add New Client")

No comments:

Post a Comment