UIHint DataAnnotation attribute in Asp.net MVC3 Razor

  1. The UIHint attribute as the name itself suggest gives the Asp.net MVC run time the name of a template to use when rendering output with the templated helpers like (DisplayFor and EditorFor).
  2. The UIHint attribute accepts the name of the Editor template to use to render the content on UI.

Example :

We have a view model where I have Gender property. I do not want gender property to be of type list. I want gender property to be of type string or bool. We are going to use EditorForModel to render the form. So, Editor for model, will not create radio button for string or bool property. It will create textbox for string and checkbox for bool.
                But we want to render two radio buttons. We will use EditorTemplate to render RadioButtons and will use UIHint to indicate which template to use.

ViewModel :


We have a Gender property of type string. We have used UIHint DataAnnotation attribute to indicate MVC to use EditorTemplate  named Gender to render controls.  

EditorTemplate :

We have created a EditorTemplates folder inside shared folder. We have created a new View named Gender.

@Html.Label("Gender","Male")
@Html.RadioButton("Gender","Male")
@Html.Label("Gender","Female")
@Html.RadioButton("Gender","Female")

View :

On View we have used EditorForModel to render controls for our ViewModel.



@model CustomValidation.Models.Register

@{
    ViewBag.Title = "Register";
    Layout = null;
}



<h2 align="center">Register</h2>
@using (Html.BeginForm("Welcome","Register",new {@id = "formClass"}))
{
    <fieldset style="width:400px;">
    <legend>Registration Form</legend>
    @Html.EditorForModel("Register")
    <br /><br />
    <input type="submit" value="Submit" />
    </fieldset>
}

The EditorForModel renders controls for all the properties in the View model. It uses the Gender EditorTemplate to render controls for Gender property.

UI :




The two Radio buttons are rendered for Gender property as expected.

Rendered HTML :


<label for="Gender_Gender">Male</label>
<input id="Gender_Gender" name="Gender.Gender" type="radio" value="Male" />
<label for="Gender_Gender">Female</label>
<input id="Gender_Gener" name="Gender.Gener" type="radio" value="Female" />

0 comments:

Post a Comment