Createing Custom Strongly Type or Model Bound HTML Helper Method

Kailash Chandra Behera | Wednesday, September 21, 2016

Introduction

In my previous article I have discussed the different ways of createing Custom HTML Helper, Now in this article we will discuss how to create Strongly type or Model Bound HTML Helper.

Getting Started

In my previous article we have discussed that there are two ways (Extension method approach and static method approach)to create Custom HTML Helpers, Now in this article we will demonstrate to create Custom Model Bound HTML Helper using above two approaches.

Friends you might have thought that create Custom Model Bound HTML Helpers is very default task. If you this kind of thought, in technically I will say release from mind.Because it's very easy and just four steps required to create as given below.

  1. Retrieve Bound Field information of Model
  2. Retrieve Validation information of Model
  3. Setting user html attributes of helper
  4. Setting above stuffs to control

Retrieve Bound Field information of Model

Above heading says that first you need to retrive metada information ( field name,)of Model that will help you to set attributes of HTML element(control) like name, id, value etc . The below code helps retriving.
 var fieldName = ExpressionHelper.GetExpressionText(expression);  
 var fullBindingName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName);  
 var fieldId = TagBuilder.CreateSanitizedId(fullBindingName);  
 var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);  
 var value = metadata.Model;  
The first line helps to get name field of model that is set in lambda expression with control in view as like in below html
  @Html.TextBoxFor(model => model.Name)  
The GetExpressionText method of ExpressionHelper class helps to get the bound name field of control. The second line retrieves full bound name of model from view context and the last line of code create id for custom helper with the help of CreaeSanitizedID function of TagBuilder class.
Little infor About the classes
ExpressionHelper: Provides a helper class to get the model name from an expression.
TagBuilder: Contains classes and properties that are used to create HTML elements. This class is used to write helpers, such as those found in the System.Web.Helpers namespace.

Retrieve Validation information of Model

The validation information helps to valid controls while user doing submit or post page.Hence the second step is to set the validation details that user sets using data annotation in model. the below code retrieves validation information of model and applies to custom control.
 var validationAttributes = htmlHelper.GetUnobtrusiveValidationAttributes(fullBindingName, metadata);  
 foreach (var key in validationAttributes.Keys)  
  {  
    NumTextBoxTag.Attributes.Add(key, validationAttributes[key].ToString());  
  }  
Above code retrives validation attributes of modes that user sets to field using data annotation in model with help of GetUnobtrusiveValidationAttributes function of HtmlHelper class and using of foreach loop sets the validation attributes to control.

Setting user html attributes of helper

The third step is to set user setting to helper that user applies in view, for example classes, styles and java script functions etc. as html attributs as like below code.
 @Html.TextBoxFor(model => model.Name, htmlAttributes: new { lass = "control-label col-md-2" })  
You can set two types of parameter in your html helper method to get user setting details, one is having object data type and other dictionary. The below code demonstrates how to set html attributes to html helper.
 NumTextBoxTag.MergeAttributes(new System.Web.Routing.RouteValueDictionary(htmlAttributes));  
 IDictionary<string, object> validationAttributes = htmlHelper.GetUnobtrusiveValidationAttributes(fullBindingName, metadata);  
       foreach (var key in validationAttributes.Keys)  
       {  
         NumTextBoxTag.Attributes.Add(key, validationAttributes[key].ToString());  
       }  

The first line helps to set html attributes when you are receiving that as object data type and the second line when you have disctionary parameter in helper method.

Setting above stuffs to control

 TagBuilder NumTextBoxTag = new TagBuilder("input");  
 NumTextBoxTag.MergeAttribute("type", "number");  
 NumTextBoxTag.MergeAttribute("name", fullBindingName);  
 NumTextBoxTag.MergeAttribute("id", fieldId);  
 NumTextBoxTag.MergeAttribute("value", value.ToString());  
 NumTextBoxTag.Attributes.Add(key, validationAttributes[key].ToString());  
 NumTextBoxTag.MergeAttributes(new System.Web.Routing.RouteValueDictionary(htmlAttributes)); 
 MvcHtmlString.Create(NumTextBoxTag.ToString(TagRenderMode.SelfClosing)); 
The above code create html helper, the TagBuilder class Contains classes and properties that are used to create HTML elements. This class is used to write helpers, such as those found in the System.Web.Helpers namespace. The create method of MvcHtmlString class Creates an HTML-encoded string using the specified text value.

Above are the stpes to create Custom Bound HTML Helper, In my next two article I will give demonstration how to create Custom Strongly Type Or Model Bound Helper Method using Extension Method and Static Method approach.
Demonstrations

  1. Creating Custom Model Bound HTML Helper using Extension Method
  2. Creating Custom Model Bound HTML Helper using Static Method

Summary

In this article we have discussed how to create Custom Model Bound HTML Helper, Hope this artcile may helpful to you.

Thanks


No comments: