Saturday, April 18, 2015

MVC - HTML Helpers

With MVC, HTML helpers are much like traditional ASP.NET Web Form controls.
Just like we have web form controls in ASP.NET, HTML helpers are used to modify HTML. Infact HTML helpers are more lightweight. 

Unlike Web Form controls, an HTML helper does not have an event model and a view state.

People coming from the asp.net web forms background are used to putting the ASP.NET server control on the page using the toolbox. When we work with ASP.NET MVC application there is no toolbox available to us from where we can drag and drop HTML controls on the view.

In most cases, an HTML helper is just a method that returns a string.
With MVC, you can create your own helpers, or use the built in HTML helpers.

1. Inline Html Helpers
2. Built-In Html Helpers
3. Custom Html Helpers

Lets explore 
1. Inline Html Helpers
Can create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.
@helper ListingProducts(string[] products)
 {
 <ol>
 @foreach (string item in products)
 {
 <li>@product</li>
 }
 </ol>
 }

 <h3>Software courses:</h3>

 @ListingProducts(new string[] { ".Net", "Java", "PHP" })

 <h3>Course List:</h3>

 @ListingProducts(new string[] { "Join in .Net course", "Join in Java", "Join in PHP" })

2. Built-In Html Helpers
These Helpers are extension methods of the HtmlHelper class. The Built-In Html helpers can be divided into three categories-
  a. Standard Html Helpers
  b. Strongly Typed HTML Helpers
  c. Templated HTML Helpers
a. Standard Html Helpers
These helpers are used to render the most common types of HTML elements like as HTML text boxes, checkboxes etc. 
Find below the most common standard html helpers.

HTML Element
Example
TextBox
@Html.TextBox("txtUserName", "val") 
Output: <input id="txtUserName" name="txtUserName" type="text" value="val" />
TextArea
@Html.TextArea("Textarea1", "val", 5, 15, null) 
Output: <textarea cols="15" id="Description" name="Description" rows="5">val</textarea>
Password
@Html.Password("txtPassword", "val") 
Output: <input id="txtPassword" name="txtPassword" type="password" value="val" />
Hidden Field
@Html.Hidden("Hidden1", "val") 
Output: <input id="Hidden1" name="Hidden1" type="hidden" value="val" />
CheckBox
@Html.CheckBox("chkbxMarried", false) 
Output: <input id="chkbxMarried" name="chkbxMarried" type="checkbox" value="true" /> <input name="myCheckbox" type="hidden" value="false" />
RadioButton
@Html.RadioButton("rdbtnPaid", "val", true) 
Output: <input checked="checked" id="rdbtnPaid" name="rdbtnPaid" type="radio" value="val" />
Drop-down list
@Html.DropDownList (“ddlGender”, new SelectList(new [] {"Male", "Female"})) 
Output: <select id="ddlGender" name="ddlGender"> <option>M</option> <option>F</option> </select>

b. Strongly Typed HTML Helpers
These helpers are used to render the most common types of HTML elements in strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements are created based on model properties.
The strongly typed HTML helpers work on lambda expression. The model object is passed as a value to lambda expression, and you can select the field or property from model object to be used to set the id, name and value attributes of the HTML helper. A list of most common strongly-typed html helpers is given below:


HTML Element
Example
TextBox
@Html.TextBoxFor(m=>m.Name) 
Output: <input id="Name" name="Name" type="text" value="Name-val" />
TextArea
@Html.TextArea(m=>m.Address , 5, 15, new{})) 
Output: <textarea cols="15" id="Address" name=" Address " rows="5">Addressvalue</textarea>
Password
@Html.PasswordFor(m=>m.Password) 
Output: <input id="Password" name="Password" type="password"/>
Hidden Field
@Html.HiddenFor(m=>m.UserId) 
Output: <input id=" UserId" name=" UserId" type="hidden" value="UserId-val" />
CheckBox
@Html.CheckBoxFor(m=>m.IsApproved) 
Output: <input id="Checkbox1" name="Checkbox1" type="checkbox" value="true" /> <input name="myCheckbox" type="hidden" value="false" />
RadioButton
@Html.RadioButtonFor(m=>m.IsApproved, "val") 
Output: <input checked="checked" id="Radiobutton1" name="Radiobutton1" type="radio" value="val" />
Drop-down list
@Html.DropDownListFor(m => m.Gender, new SelectList(new [] {"Male", "Female"})) 
Output: <select id="Gender" name="Gender"> <option>Male</option> <option>Female</option> </select>
Multiple-select
Html.ListBoxFor(m => m.Hobbies, new MultiSelectList(new [] {"Cricket", "Chess"})) 
Output: <select id="Hobbies" multiple="multiple" name="Hobbies"> <option>Cricket</option> <option>Chess</option> </select>

c. Templated HTML Helpers
These helpers figure out what HTML elements are required to render based on properties of your model class. This is a very flexible approach for displaying data to the user, although it requires some initial care and attention to set up. To setup proper HTML element with Templated HTML Helper, make use of DataType attribute of DataAnnotation class.
For example, when you use DataType as Password, A templated helper automatically render Password type HTML input element.
Templated Helper
Example
Display
Renders a read-only view of the specified model property and selects an appropriate HTML element based on property’s data type and metadata. 
Html.Display("Name")
DisplayFor
Strongly typed version of the previous helper 
Html.DisplayFor(m => m. Name)
Editor
Renders an editor for the specified model property and selects an appropriate HTML element based on property’s data type and metadata. 
Html.Editor("Name")
EditorFor
Strongly typed version of the previous helper                                                                             
Html.EditorFor(m => m. Name) 

3. Custom Html Helpers
You can also create your own custom helper methods by creating an extension method on the HtmlHelper class or by creating static methods with in a utility class.

public static class CustomHelpers
{
 //Save Button Helper
 public static MvcHtmlString SaveButton(this HtmlHelper helper, string 
 buttonText)
 {
 string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
 return new MvcHtmlString(str);
 }
 //Readonly Strongly-Typed TextBox Helper
 public static MvcHtmlString TextBoxFor<TModel, TValue>(this 
 HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>>
 expression, bool isReadonly)
 {
 MvcHtmlString html = default(MvcHtmlString);

 if (isReadonly)
 {
 html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
 expression, new { @class = "readOnly",
 @readonly = "read-only" });
 }
 else
 {
 html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
 expression);
 }
 return html;
 }
}
The End.

No comments:

Post a Comment