Creating More Complex HTML Helpers And Using Those In MVC

In this article, I will show you how you can create some complex custom HTML Helper controls and modify them according to your need to use them accordingly.

For simple custom HTML controls, I have written another article. Just refer to it for the basics and then come back here. Click here for the previous article.

What will we create?

In this article, I will show you how to create custom controls, how you can bind them to your model properties, how you can populate them, and how you can pass HTML attributes to them.

Let’s get started.

We will create a static class with a static method in it and the return type of the method will be MvcHtmlString and this can be found in System.Web.Mvc namespace. We will create a custom dropdown control and will bind it, populate it etc.

In order to achieve it, we have to pass some parameters to our functions. Thus, our function will look something, as shown below.

  1. public static MvcHtmlString CustomDropDown < TModel, TValue > (this HtmlHelper < TModel > html, Expression < Func < TModel, TValue >> expression, List < string > names, object htmlAttributes) {}  
As you can see this, it is just the declaration of the function.

Lets understand these parameters first.
  • First one is this HtmlHelper<TModel> html
    We can use this control in view with @Html.

  • Second one is Expression<Func<TModel, TValue>> expression
    We can pass our lamda expression to bind this control with our model’s property. Here an expression is found in System.Linq.Expression namespace.

  • Third one is List<string> names
    This parameter is to populate our control. As we are creating a drop down control, so in drop down control, we see some values in a list and those values will be passed in this list. You can modify this according to your need and requirement.

  • Fourth one is object htmlAttributes
    We can pass HTML attributes at run time in order to add some Id or classes to our controls.

Now that I have explained about the parameters, let's just look at the entire function’s body.

  1. public static MvcHtmlString CustomDropDown < TModel, TValue > (this HtmlHelper < TModel > html, Expression < Func < TModel, TValue >> expression, List < string > names, object htmlAttributes) {  
  2.     var fieldName = ExpressionHelper.GetExpressionText(expression);  
  3.     var fullBindingName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName);  
  4.     var fieldId = TagBuilder.CreateSanitizedId(fullBindingName);  
  5.     var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);  
  6.     var value = metadata.Model;  
  7.     TagBuilder tagBuilder = new TagBuilder("select");  
  8.     tagBuilder.Attributes.Add("name", fullBindingName);  
  9.     tagBuilder.Attributes.Add("id", fieldId);  
  10.     StringBuilder options = new StringBuilder();  
  11.     options.AppendLine("<option value='0' > Select </option>");  
  12.     for (int i = 0; i < names.Count; i++) {  
  13.         string singleOption = "<option value = '" + names[i].ToString() + "'>" + names[i].ToString() + "</option>";  
  14.         options.AppendLine(singleOption);  
  15.     }  
  16.     tagBuilder.InnerHtml = options.ToString();  
  17.     foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes)) {  
  18.         tagBuilder.MergeAttribute(prop.Name.Replace('_''-'), prop.GetValue(htmlAttributes).ToString(), true);  
  19.     }  
  20.     return new MvcHtmlString(tagBuilder.ToString());  
  21. }  
Here is the explanation of the code.

We will get the field name from an expression that we have just passed and then create the field Id from tag builder class’s default method, which is CreateSanitizedId.  We will obtain metadata from the lambda expression that we have passed. Afterwards, we will use tag builder class and to tag builder class; we will pass “select”. As we are creating a dropdown; dropdown’s HTML tag select, so we need to pass it.

Subsequently, we will add some attributes in the tagbuilder’s object that we have just created such as name and Id, which will be useful in an Application.

Now, let’s see the dropdown’s full HTML tag syntax.

<select>
<option value="1">Male</option>
<option value="2">Female</option>
</select>

Here, we can see the basic syntax of select tag in HTML. Now, we have created the select tag by passing it to tag builder class. Now, we need to create an option tag. For it, we will use StringBuilder class. First option of a dropdown will always will be to select due to which we have added it and for rest of the options, we have started a for loop inside which we will create our options tag from the names list provided in a parameter.

Once we are done, we will add options to the innerHtml property of the tag builder class’s object. To apply HTML attributes, which we have just passed object as htmlAttributes as our last parameter. Now, we will start a foreach loop in order to get every property from htmlAttirbute passed and applied it to our tagbuilder.

Once we are done with foreach loop, we can return the MvcHtmlString. Our entire method looks, as shown below.

model

In order to use this, we will create a model, which we will bind it to our view and the model will contain a list of dropdown values and a variable, which we will bind our dropdown to.

model

Now, we will bind our view to our model by writing this line at the top of our view.

@model HelperClassesDemo.Models.TestModel

We will add our control in the form, as shown below.

@Html.CustomDropDown(a=>a.SelectedValue,Model.dropDownValuesList,new { @class="form-control"})

Now, our entire view looks, as shown blow.

model

As you can see, I have added bootstrap jQuery and CSS in order to preview form-control class, which is in bootstrap and I have added a submit button.

Now, we will populate this dropdown by passing the model to the view.
  1. public ActionResult Index() {  
  2.     TestModel model = new TestModel();  
  3.     List < string > names = new List < string > ();  
  4.     names.Add("BMW");  
  5.     names.Add("Audi");  
  6.     names.Add("Wolkswagon");  
  7.     model.dropDownValuesList = names;  
  8.     return View(model);  
  9. }  
In the code mentioned above, you can see that I have added few names in the list and added it to the model.

Now, in submit (Post) method, we will redirect the user to home. Hence, our entire controller looks, as shown below.

model

Now, we will run it. The output will be, as shown.

model
model

Summary

In this article, we have seen how to create our own custom HTML controls, modify them according to our need, bind them to our model properties.

I have made a video about this in detail. Please go and check. Here is the YouTube Link

Here is the link of my previous blog, which was about simple MVC helpers.

Up Next
    Ebook Download
    View all
    Learn
    View all