Monday, August 31, 2015

Custom HTML Helpers without HTML Attributes



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 Div(this HtmlHelper helper, string Id, Func<object, object> innerHTML = null)
 {
     //Declare StringBuilder to hold the control's markup
     var sb = new StringBuilder();

     //This reads the markup dictionary from the input parameters
     var markup = (innerHTML == null ? "" : innerHTML.DynamicInvoke(helper.ViewContext).ToString());

     //This constructs the markup for final control
     sb.Append($"<div id='div_{Id}' class='caption'>{markup}</div>");
    
     //Finally returns the control markup as 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.Div("divMyCustomDiv", @<text>
         <div>My Custom Markup</div>
         <span>More Stuff</span>
         </text>)

No comments:

Post a Comment