HTML helpers helps to render HTML controls (Like TextBox, label,Checkbox etc) in the view.Suppose you want to display a TextBox and Label on the view,you need to write below html helper code in view:--
Built-In Html Helpers are extension methods on the Html Helper class. It's divided into three categories-
Standard Html Helpers:- It's used to render the most common types of HTML elements like as HTML text boxes, label, checkbooks,select etc. A list of most common standard html helpers is given below :--
@Html.DropDownList (DropDownList1, new SelectList(new [] {"Male", "Female"}))
Output:
Multiple-select
Html.ListBox(ListBox1, new MultiSelectList(new [] {"Cricket", "Chess"}))
Output:
Strongly Typed HTML Helpers :- It's also used to render the most common types of HTML elements in strongly typed view like as HTML text boxes, label, checkboxes,dropdown etc. The HTML elements are created based on model properties. It works 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:
Password
@Html.PasswordFor(m=>m.Password)
Output:
CheckBox
@Html.CheckBoxFor(m=>m.IsApproved) Output:
Drop-down list
@Html.DropDownListFor(m => m.Gender, new SelectList(new [] {"Male", "Female"})) Output:
Templated HTML Helpers :-Templated helpers figure out what HTML elements are required to render based on properties of your model class. It's 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 Data Annotation class.
Example:-When you use DataType as Password, A templated helper automatically render Password type HTML input element.
Templated Helper
Example
Editor
Renders an editor for the specified model property and selects an appropriate HTML element based on propertys data type and metadata.
Html.Editor("Name")
EditorFor
Strongly typed version of the previous helper
Html.EditorFor(m => m. Name)
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
{
//Submit Button Helper
public static MvcHtmlString SubmitButton(this HtmlHelper helper, string
buttonText)
{
string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
return new MvcHtmlString(str);
}
0 Comment(s)