Custom Label HTML Helper with model binding in MVC3 Razor
- In MVC3 Razor we have HTML helpers to render different controls.
- Instead of using these helpers we can create our own helper classes and methods and use them as we want.
- The creation of custom helpers provides flexibility to change the attributes and style of the control that renders.
- In this article we will create Custom HTML helper for Label with model binding to render text.
Following are the steps :
First we will create a folder named CustomHelper. We will include a class file named CustomHelperBinding.cs, which will hold code for Custom Label control.
We have created the folder and the class file as mentioned earlier as shown in the above image.
The class file looks as below :
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Linq.Expressions; using System.Web.Routing; namespace CustomHtmlHelpers.CustomHelpers { public static class CustomHelperBinding { public static MvcHtmlString CustomLabelBinding<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<Model, TValue>> expression, object htmlAttributes) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); string htmlFieldName = ExpressionHelper.GetExpressionText(expression); string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); if (String.IsNullOrEmpty(labelText)) { return MvcHtmlString.Empty; } TagBuilder tag = new TagBuilder("label"); tag.MergeAttributes(new RouteValueDictionary(htmlAttributes)); tag.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); tag.SetInnerText(labelText); return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal)); } } }
In the above code we have created a static class having a static method. The method accepts expression i.e. linq expression which binds the control to the model property, and htmlAttributes object through which we can pass attributes to set.
We are using ModelMetaData class to fetch the metadata from the linq expression passed. The metadata contains the property details which we can use to fetch the property name and also the property value in Database.
We are using TagBuilder class to create label control. We are fetching the propertyName from the metadata and using it to set the name attribute and innerText of label control.
The method created above is extension method, and first parameter adds this method to System.Web.Mvc namespace. On view we can access this method using @Html. This method returns MvcHtmlString object. The MvcHtmlString represents a HTML-encoded string that should not be encoded again.
View :
We are binding the view with Register model. We can then use the properties defined in the Register class.
In the above view, we are using CustomLabelBinding i.e. Custom Label helper to render label. We are binding the control with FirstName property of Register model. We are also passing the style attribute as htmlAttribute object.
UI :
The FirstName Label is rendered with style applied to it.
Rendered HTML :
<label for="FirstName" style="color:Red;">FirstName</label>
This is how we create Custom Label helper with model binding support and fulfill our project needs.
Hola , mi duda es la siguiente , tengo una clases :
ReplyDeletepublic class ClassCreateViewModelPacientes
{
public vCasoEmergencia casoEmergencia { get; set; }
public vPacientes pacientes { get; set; }
}
La cual es sus propiedades son del tipo de las clases de mi modelo, hago esto con el fin de pasar dos modelos a mi vista, y ps con el codigo que ustedes me dan no me funciona