Tata Birla and sangla and mitra and poo and goo
YahaParAdd
- We commonly use HTML helpers and model binding while working with MVC Razor.
- MVC framework smartly renders HTML for different type of data like textbox for string or int and checkbox for bool proeprty, when EditorFor or EditorForModel helper is used to render the control.
- We often have requirement where we want something more like rendering dropdown for model's property of type enum.
- This is where editor template comes to rescue the situation.
- In this example, we will render a dropdown control for enum type model property.
ViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace BindingDropdownToEnum.Models
{
public class DropdownModel
{
[UIHint("DropDownList")]
public players playerList { get; set; }
}
public enum players
{
Fabregas = 1,
Rocisky = 2,
Ozil = 3,
Cazorla = 4
}
}
In the above view model we have created an enum named players. We have created one class which has one poperty of type players (i.e. enum). We have used DataAnnotation attribute UIHint to indicate MVC framework the editor template to pick while rendering control for the property. In the above example, we are asking MVC framework to use DropDownList cshtml file under Editor Template folder.
View:
@model BindingDropdownToEnum.Models.DropdownModel
@{
ViewBag.Title = "DropdownBinding";
}
<h2>DropdownBinding</h2>
@Html.EditorForModel()
We have used EditorForModel to render controls for model properties.
EditorTemplate:
@using BindingDropdownToEnum.Models
@Html.DropDownList("playerList", Enum.GetValues(typeof(players)).Cast<players>().Select(c => new SelectListItem { Text = c.ToString(), Value = c.ToString() }))
In the above EditorTemplate we have rendered a dropdownlist control using the enum. When the view is rendered, the UIHint attribute indicates MVC framework to use EditorTemplate to render the control.
The editor templates are created under EditorTemplates folder which is underShared folder. Thus using EditorTemplates we can render any control for any type of property using EditorForModel or EditorFor HTML helper.

0 comments:
Post a Comment