SPS Home    >   Dgreath    >   MVC HTML HELPERS

MVC HTML Helpers

HTML Helpers assist in development of .NET MVC coding by providing easy connection of models to markup. In addition to the primary arguments noted, each method takes an additional htmlAttributes parameter in either a IDictionary<string, object> or anonymous type new {@class = "form-control"} type.  Listed below are the standard helpers available that generate markup from a view:

BeginForm / BeginRouteForm / EndForm

Creates form markup to open and close a form.

BeginForm is used to mark the beginning of the form and provides basic routing that works for most cases.

BeginRouteForm is used to mark the beginning of the form and provides advanced routing for special cases.

EndForm is used to mark the end of the form.

BeginForm or BeginRouteForm can also be implemented with Razor 'using' form which eliminates the need for the EndForm using @HtmlBeginForm(attributes){form markup}

Reference: System.Web.Mvc.Html.FormExtensions.cs


Propery Name Helpers

The following helpers are used to render markup related to Property Names:

DisplayName / DisplayNameFor / DisplayNameForModel

Renders the model property's 'Display Name' from the[Display(Name = "value")] annotation in the model.  If the annotation is not present, defaults to the model property name. The result is clean with no additional markup present. For the model name, use the [DisplayName("value")] annotation instead since the display annotation won't work for the model.  Note: Display overrides DisplayName if both are declared on the same property.

DisplayName("propertyName") is the nontyped version  to access property display name by string expression reference to the ViewBag.

DisplayNameFor(model => model.propertyName) is the strongly typed version to access property display name by lambda expression against the view's model.

DisplayNameForModel() renders the model's display name against the view's current model.

Reference: System.Web.Mvc.Html.DisplayNameExtensions.cs

Id / IdFor / IdForModel

Render model property html Id with no markup. The results returned depend on whether it is being rendered iteratively or non-iteratively. When used non-iteratively, the value returned will be the actual property name (essentially the same as passed in).  When used iteratively, the value returned will include the iteration name in the form "item_PropertyName" where the iteration name is "item". As a practical matter, this helper is only useful in iterations since you already know the property name when you call it. These are used to provide hooks for Javascript and Css.

Id("propertyName") is the nontyped version to access property's id by string expression reference to the ViewBag.

IdFor(model => propertyName) is the strongly typed version to render the property's id by lambda expression against the view's model.

IdForModel() provides Id support for templates.

Reference: System.Web.Mvc.Html.NameExtensions.cs

Name / NameFor / NameForModel

Render model property html name with no markup. The results returned depend on whether it is being rendered iteratively or non-iteratively. When used non-iteratively, the value returned will be the actual property name (essentially the same as passed in).  When used iteratively, the value returned will include the iteration name in the form "item.PropertyName" where the iteration name is "item". As a practical matter, this helper is only useful in iterations since you already know the property name to call it. These are provided to provide hooks for JavaScript and Css.

Name("propertyName") is the nontyped version to render the property's actual name by string reference to the ViewBag.

NameFor(model => model.proertyName) is the strongly typed version to render property name by lambda expression against the view's model.

NameForModel(() provides Name support for templates.

Reference: System.Web.Mvc.Html.NameExtensions.cs


Propery Value Helpers

The following helpers are used to render markup related to Property values:

CheckBox / CheckboxFor

Renders checkbox form input control markup for a specified boolean property.

CheckBox("propertyName") is the nontyped version  to access property value by string expression reference to the ViewBag.

CheckBoxFor(model => model.propertyName) is the strongly typed versionto access property value by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.InputExtensions.cs

DisplayText / DisplayTextFor

Renders the ModelMetadata.SimpleDisplayText which is the unfomatted version of the property's vaue.

DisplayText("propertyName") is the nontyped version  to access the property's SimpleDisplayText by string expression reference to the ViewBag.

DisplayTextFor(model => model.propertyName) is the strongly typed version to access the property's SimpleDisplayText by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.DisplayTextExtensions.cs

DropDownList / DropDownListFor

Generates select/option markup for single item selection from a SelectList in the form of IEnumerable<SelectListItem>. This helper uses the  property name to indicate the selection along with a separate SelectList to provide the options to choose.

DropDownList("propertyName", SelectList) is the nontyped version to render a drop down list by string expression reference to the ViewBag.

DropDownListFor(model => model.property, SelectList) is the strongly typed versiono render a drop down list by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.SelectExtension.cs

EnumDropDownListFor

Renders select/option markup from a SelectList in the form of an enumeration.

EnumDropDownListFor(model => model.propertyName, Enumeration) is strongly typed o render property value by lambda expression against the view's model. Similar to the DropDownList, it uses an enumeration to populate the options instead of an IEnumerable type.

Reference: System.Web.Mvc.Html

Hidden / HiddenFor

Renders hidden form input control markup for a specified property value.

Hidden("propertyName") is the nontyped version to access property value by string expression reference to the ViewBag.

HiddenFor(model => model.propertyName) is the strongly typed version to access property value by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.InputExtensions.cs

ListBox / ListboxFor

Renders select/option markup that allows for multiple item selection from a SelectList in the form of an IEnumerable<SelectListItem>.

ListBox("propertyName", SelectList) is the nontyped version to render a list by string expression reference to the ViewBag.

ListBoxFor(model => model.propertyName, SelectList) is the strongly typed version to render a list by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.SelectExtension.cs

Password / PasswordFor

Renders read/write password form input control markup for a specified property value.

Password("propertyName") is the nontyped version to access property value by string expression to the ViewBag.

PasswordFor(model => model.propertyName) is the strongly typed versionto access property value by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.InputExtensions.cs

RadioButton / RadioButtonFor

Renders read/write radiobutton form input control markup markup for a specified property value.

RadioButton("propertyName") is the nontyped version to access property value by string expression to the ViewBag.

RadioButtonFor(model => model.propertyName) is the strongly typed versionto access property value by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.InputExtensions.cs

TextArea / TextAreaFor

Renders read/write text area markup for a specified  property value.

TextArea("propertyName") is the nontyped version to render property value by string expression reference to the ViewBag.

TextAreaFor(model => model.propertyName) is the strongly typed version to render property value by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.TextAreaExtensions.cs

TextBox / TextBoxFor

Renders read/write textbox form input control markup for a specified property value.

TextBox("propertyName") is the nontyped version to provide editing access to a property value by string expression against the ViewBag.

TextBoxFor(model => model.propertyName) is the strongly typed version to provide editing access property value by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.InputExtensions.cs

Value / ValueFor / ValueForModel

Returns the formatted read only value of a specified model property. The result is clean with no additional markup.

Value("propertyName") is the nontyped version to access property value by string expression against the ViewBag.

ValueFor(model => model.propertyName) is the strongly typed version to access property value by lambda expression against the view's model.

ValueForModel() renders the fully qualified name of the current model.

Reference: System.Web.Mvc.Html.ValueExtensions.cs


Templated HTML Helpers

The following helpers are designed and intended to be used as part of the automatic scaffolding process. These helpers render markup based either on the data type of the property, or as specified with DataAnnotations in the model. It is possible to over-ride the model's Data Annotation by specifying the desired DataType you need in the helper's arguments. Each helper renders differently depending on whether it is targeted to a Display (read only) or Editor (read/write) helper.

Display / DisplayFor / DisplayForModel

Renders either the plain text or formatted value of model properties for read only rendering.

Display("propertyName") is the nontyped version to access property's value by string expression reference to the ViewBag.

DisplayFor(model => model.propertyName) is the strongly typed version to access property's value by lambda expression against the view's model.

DisplayForModel() renders a list of all properties and values contained in the current model.

Templates include: boolean, Boolean Checkbox, Boolean Template dropdownlist, collection, decimal, hidden, multiline, password, string, phone number, url, email, date, time, number, and color.

Reference: System.Web.Mvc.Html.DisplayExtensions.cs

Editor / EditorFor / EditorForModel

Calls one of various editor templates depending on the type of data to be editable.

Editor("propertyName") is the nontyped version to allow editing a property value by string expression reference to ViewBag.

EditorFor(model => model.propertyName) is the strongly typed version  to render property value by lambda expression against the view's model.

EditorForModel()  returns a list of all properties rendered as input controls with associated labels.

Templates include: boolean, Boolean Checkbox, Boolean Template dropdownlist, collection, decimal, hidden, multiline, password, string, phone number, url, email, date, time, number, and color.

Reference: System.Web.Mvc.Html.EditorExtensions.cs

Label / LabelFor / LabelForModel

Creates templated label markup for a specified property which reflects the DisplayName, if available, or the propertyName otherwise.

Label("propertyName") is the nontyped version  to render property name as a label by string expression reference to the ViewBag.

LabelFor(model => model.propertyName) is the strongly typed version to render property name as a label by lambda expression against the view's model.

LabelForModel() renders the current model's DisplayName as a label.

Reference: System.Web.Mvc.Html.LabelExtensions.cs


Validation HTML Helpers

Validate / ValidateFor

Triggers validation process for a specified model property.

Validation("propertyName") is the nontyped version enable validation of a property value by string expression against the ViewBag.

ValidationFor(model => model.propertyName) is the strongly typed version to enable validation of  property value by lambda expression against the view's model.

Reference: System.Web.Mvc.Html.ValidationExtensions.cs

ValidationMessage / ValidationMessageFor

Creates markup to display a hidden <span> element to display individual messages where validation annotations have been declared on the property.

ValidationMessage("propertyName") is the nontyped version to associate the property by string expression against the ViewBag.

ValidationMessageFor(model => model.property) is the strongly typed version to associate the property by lambda expression against the view's model.

Standard validation annotations include: Compare, Required, String Length, Min/Max values, Range, Regular Expression. In addition there are other specialized annotations that provide validation support.

Reference: System.Web.Mvc.Html.ValidationExtensions.cs

ValidationSummary

Creates markup to display a hidden <ul> listing all validation messages contained in the form. When set false, the summary displays prior to form submission when the submit condition is triggered. When false, the summary does not display.  See ValidationMessage for more details. When false, summary is rendered.

ValidationSummary(false)

Reference: System.Web.Mvc.Html.ValidationExtensions.cs


Non HTML Helpers

The following helpers do not generate markup from the ViewBag or models. Some do generate special markup as noted.

Action / RenderAction

Action invokes the specified action and returns the result as an html string. This allows a child action to be embedded in a parent view.

RenderAction immediately emits a call to HttpContext.Server.Execute().

Reference: System.Web.Mvc.Html.ChildActionExtensions.cs

ActionLink / RouteLink

Creates anchor "A" markup. Both methods generate the same results, however, the ActionLink is a shorthand version of the full blown RouteLink.

ActionLink("linktext", "action","controller", route, htmlAttributes) renders anchor tag based on Controller/Action/Route only.

RouteLink("linktext", route, htmlAttributes) allows creation of advanced routing that require more specific detail than ActionLinks provide.

Reference: System.Web.Mvc.Html.LinkExtensions.cs

AntiForgeryToken

AntiForgeryToken()

Generates hidden form field markup that can be evaluated when form is submitted.

Each associated controller action must be decorated with [ValidateAntiForgeryToken()].

Reference: System.Web.Mvc.ValidateAntiForgeryTokenAttribute.cs

AttributeEncode

Converts an object or string to an Html encoded string. Mostly used internally.

EnableClientValidation(false)

EnableClientValidation()

Enables/disables validation by client scripts. Normally this feature is enabled by default by the ClientValidationEnabled key in web.config appSetting set to true. You can use this to selectively disable client side validation.

EnableUnobtrusiveJavascript(false)

EnableUnobtrusiveJavascript(false)

Enables/disables unobtrusive javascripts to run on the client. Normally this feature is enabled by default by the UnobtrusiveJavascriptEnabled key in web.config appSetting set to true. You can use this to selective disable unobtrusive javascript.

Encode

Converts the value of the specified object to HTML encoded string.

Equals

Determines whether the specified object is equal to the current object.

FormatValue

Converts an object into the specified format.

GetHashCode

The hash function for a given type.

GetType

Gets the type of the current instance.

GetUnobtrusiveValidationAttributes

Gets the collection of unobtrusive validation attributes.

Html5DateRenderingMode

Gets or sets html5 date mode.

HttpMethodOveride

Returns hidden field markup that identifies the override method for the specified verb that represents the data transfer method used by the client.

IteratingModelFor

Research needed Not clear as to the use for this. Probably used internally.

NonIteratingModelFor

Research needed Not clear as to the use for this. Probably used internally.

Partial / RenderPartial

Executes and optionally renders a specified partial view.

Partial("PartialViewName") executes partial view and returns result as an html string.

RenderPartial("PartialViewName") executes partial view and renders to the client.

References: System.Web.Mvc.Html.PartialExensions.cs and System.Web.Mvc.Html.RenderPartialExtensions.cs

Raw

Returns markup that is *not* html encoded.

SetValidationMessageElement

Set element name used to wrap the validation message generated by the @Html.ValidationMessage.

SetValidationSummaryMessageElement

Set element name used to wrap the validation message generated by the @Html.ValidationSummary.

ToString

Returns a string that represents the current object.


HTML Data Structures

Below are the various data structures available.

RouteCollection

Gets or sets the collection of routes for the application.

ViewBag

Gets the View Bag.

ViewContext

Gets or sets the context information about the view.

ViewData

Gets the strongly typed data dictionary

ViewDataContainer

Gets or sets the ViewDataContainer