Html helpers in MVC Part 3 | Templated html helpers in mvc

html helpers mvc part 3

Templated html helpers in ASP.NET MVC

Using built in html helpers such as html.textbox, html.checkbox we are able to generate html elements but we have to decide in advance what kind of element is needed to represent a model property. If type of model property changes we also need to make change in html helper used for that property.

Using templated helpers in ASP.NET mvc we specify the model property for which to display html element and MVC framework figure out what kind of element to be displayed for model property.

This approach is more flexible but it requires initial care and attention to set up.

In this ASP.NET MVC tutorial we are going to see following topics about templated html helpers in MVC.

  • Types of templated html helpers in mvc
  • Whole-model templated helpers
  • Control editing and visibility using metadata
  • Metadata for data values
  • Metadata to select a dispaly template
  • Creating a generic template

Types of templated html helpers in mvc :

Helper Example Description
Display Html.Display(“FirstName”) Renders a read-only view of the specified model property, choosing an HTML element according to the property’s type and metadata
DisplayFor Html.DisplayFor(x => x.FirstName) Strongly typed version of the previous helper
Editor Html.Editor(“FirstName”) Renders an editor for the specified model property, choosing an HTML element according to the property’s type and metadata
EditorFor Html.EditorFor(x => x.FirstName) Strongly typed version of the previous helper
Label Html.Label(“FirstName”) Renders an HTML <label> element referring to the specified model property
LabelFor Html.LabelFor(x => x.FirstName) Strongly typed version of the previous helper
DisplayForModel Html.DisplayForModel() Renders a read-only view of the entire model object
EditorForModel Html.EditorForModel() Renders editor elements for the entire model object
LabelForModel Html.LabelForModel() Renders an HTML <label> element referring to the entire model object

To understand how to use templated helpers lets create a code example for templated helpers in mvc.
I have created a web application project in MVC using empty template and added a Person Model class along with a couple of supporting types :

I have created a Home controller having following content :

Add following content to the _Layout.cshtml :

In RouteConfig.s file add the following routes :

I am creating a view CreatePerson.cshtml in which I have used EditorFor and Editor helper methods.

You can see the effect of changes when you start the app and navigate to /Home/CreatePerson URL as shown in figure.

using editor editorfor helper methods mvc

If right click page and view source you will see following html generated :

You will notice in above code that input elements are generated for editorFor and Editor helper methods according to data type of model properties.

Using LabelFor, Label, Display, DisplayFor html helpers :

These elements are used to display readonly representation of the model property.

To demonstrate these helper methods I have updated the Home controller CreatePerson action method having HttpPost attribute.

Also, create a new view DisplayPerson in Views/Home folder having following content :

You will see the following output which contains readonly view of model properties generated by lable and display helpers, when you browse to /Home/CreatePerson URL and click submit.

using helpers generate readonly view model properties

You will see following html generated when you view source of the page :

Using Whole-Model Templated Helpers :

MVC helpers also define helpers that operate on entire objects, a process known as scaffolding.
You can see in following code how I have used whole model helpers in CreatePerson.cshtml view.

You can see the effect of whole model helper in figure :

using whole model templated helper create edit form person object

Problem with the generated html is that it doesn’t correspond to the css defined in the _Layout.cshtml file.

Here is the example of the Html generated for firstname property.

I can change the appearance of the html by adding CSS classes in _Layout.cshtml that correspond to classes generated by scaffolding html helpers.

You will see the effect of adding css to _Layout.cshtml.

effect styling elements using classes defined scaffolding helpers

Control editing and visibility using metadata :

In output generated PersonId field is editable. If it is a primary key then we don’t want the user to edit it.

We can display the property as readonly by HiddenInput attribute.

You will see the output when HiddenInput attribute is set as shown in figure :

applying hiddeninput attribute display property readonly

 

If you don’t want to display property value in the output use DisplayValue=false in HiddenInput attribute

If you run the application and see the output you will see that personId field is not displayed.

Using metadata for data values:

You can also use metadata to provide instructions about how a Model property should be displayed.

Also we can control how names given to properties displayed in a view using metadata.

In following code we are applying metadata to birthdate property to display date instead of datetime using DataType attribute.

Also we have used Display attribute to control how name given to properties is displayed.

You can see the effect of applying metadata attributes in figure :

effect applying metadata attributes model properties

Following table describes most useful values of DataType enumeration.

Value Description
DateTime Displays a date and time (this is the default behavior for System.DateTime values)
Date Displays the date portion of a DateTime
Time Displays the time portion of a DateTime
Text Displays a single line of text
PhoneNumber Displays a phone number
MultilineText Renders the value in a textarea element
Password Displays the data so that individual characters are masked from view
Url Displays the data as a URL (using an HTML a element)
EmailAddress Displays the data as an e-mail address (using an a element with a mailto href)

Using metadata to select a dispaly template :

As the name suggests, templated helpers use display templates to generate html. The template that is used is based on the type of the property being processed and kind of helper being used.

I can use UIHint attribute to specify the template used to render HTML for a property :-

In above code, I have used UIHint attribute to display TextArea for firstname property when used with helpers such as EditorFor and EditorForModel.

Built-in MVC Framework view templates :

Value Effect(Editor) Effect(Display)
Boolean Renders a checkbox for bool values. For nullable bool? values, a select element is created with options for True, False, and Not Set. As for the editor helpers,but with the addition of the disabled attribute, which renders read-only HTML controls
Collection Renders the appropriate template for each of the elements in an IEnumerable sequence. The items in the sequence do not have to be of the same type. As for the editor helper
Decimal Renders a single-line textbox input element and formats the data value to display two decimal places Renders the data value formatted to two decimal places
DateTime Renders an input element whose type attribute is datetime and which contains the complete date and time Renders the complete value of a DateTime variable
Date Renders an input element whose type attribute is date and that contains the date component (but not the time) Renders the date component of a DateTime variable
EmailAddress Renders the value in a single-line textbox input element Renders a link using an HTML a element and an href attribute that is formatted as a mailto URL
HiddenInput Creates a hidden input element Renders the data value and creates a hidden input element
Html Renders the value in a single-line textbox input element Renders a link using an HTML a element
MultilineText Renders an HTML textarea element that contains the data value Renders the data value
Number Renders an input element whose type attribute is set to number Renders the data value
Password Renders the value in a single-line textbox input element so that the characters are not displayed but can be edited Renders the data value—the characters are not obscured
String Renders the value in a single-line textbox input element Renders the data value
Text Identical to the String template Identical to the String template
Tel Renders an input element whose type attribute is set to tel Renders the data value
Time Renders an input element whose type attribute is time and which contains the time component (but not the date) Renders the time component of a DateTime variable
Url Renders the value in a single-line textbox input element Renders a link using an HTML a element. The inner HTML and the href attribute are both set to the data value.

In the code example in this tutorial you may have noticed that HomeAddress property is not rendered in the view. This is because templated helper operates only on simple types such as int, bool, double, guid and DateTime.

If I have to render the complex property I have to explicitely make separate call to templated helper for that property.

You can see the effect in following figure :

display complex property explicite call temlpated helper mvc

Create a custom template :

In view generated for html helpers you can see that helper used to display role property generates text editor.

The better approach to dispaly role is dropdownlist which can be achieved by creating custom html helper template for role property so that whenever role property appeared framework generates dropdownlist using custom template.

The MVC framework looks for custom editor templates in /Views/Shared/EditorTemplate folder.

I have created EditorTemplate folder in views/Shared folder and added strongly typed view Role.cshtml inside it.

Whenever framework encounters Role property it uses this view to generate dropdownlist.

effect custom template role enumeration

 

Creating a Generic Template :

You can create a template that works for all enumerations and specify to select that template using UIHInt attribute.

To demonstrate this create a new file Enum.cshtml in the Views/Shared/EditorTemplate folder.

Add UIHint attribute to role property in person.cs file.

Using this approach you can ensure that all enum properties are displayed using select element.

Summary :

  • Using templated helpers is more flexible and time saving approach to design and maintain views.
  • If you want to generate entire view from a object model by adding just few lines of code, use whole model templated helper.
  • You can control editing, visibility and other aspects of view generated from templated helpers using metadata.
  • Define your own template to represent model property using custom editor template.
  • The MVC framework looks for custom editor templates in /Views/Shared/EditorTemplate folder.
  • You can create a template that works for all enumerations and specify to select that template using UIHInt attribute.

6 Comments

  1. This is really fascinating, You’re a very skilled blogger.
    I’ve joined your feed and look forward to looking for extra of your wonderful post.
    Also, I have shared your web site in my social networks

    Reply
  2. This is very interesting, You are an excessively skilled
    blogger. I have joined your feed and look ahead to looking for extra of your excellent post.
    Additionally, I’ve shared your site in my social networks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *