Tuesday, July 15, 2014

ASP.NET MVC HTML Helpers

There are five kinds of HTML Helpers

  • Inline HTML Helpers
  • Standard HTML Helpers
  • Strongly typed HTML Helpers
  • Templated HTML Helpers
  • Custom HTML Helpers


Inline HTML Helpers : The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates

https://mscblogs.blob.core.windows.net/media/scottgu/Media/image_45F2CF3E.png

The inline HTML Helpers can be used across multiple views by moving it to .cshtml and into the App_Code directory as illustrated below.

https://mscblogs.blob.core.windows.net/media/scottgu/Media/SNAGHTML2107b6ae_18CDBCA3.png

Standard HTML Helpers 
These helpers aer used to render the most common types of HTML Elements like textboxes, checkboxes, etc.

E.g. @Html.TextBox("Textbox1", "val") 
@Html.RadioButton("Radiobutton1", "val", true) 

Strongly Typed HTML Helpers 
These helpers are used to render the most comom types of HTML form elements like TextBoxes, CheckBoxes , but are created by model properties. 

E.g.
@Html.TextBoxFor(m=>m.Name) 
Output: <input id="Name" name="Name" type="text" value="Name-val" />


Templated HTML Helpers
These helpers figure out what HTML elements are required to render based on properties of your model class. 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.

E.g. 

Custom HTML Helpers
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);
 }

}




No comments:

Post a Comment