I am working on a .Net MVC3 application. I have a couple different models which all have an attribute or two with a DataType of varchar(1). For each of these want to have a drop down menu for Yes/No with a value of 'Y' or 'N'.
My current solution is as follows: I have a method in a public class which sends gives me my List of Yes/No values for the dropdown:
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "Yes", Value = "Y" });
items.Add(new SelectListItem() { Text = "No", Value = "N" });
return items;
In my Controller, I then set this list into the ViewBag and send it into the View:
ViewBag.YesNo = new SelectList(repository.GetYesNo(), "Value", "Text");
And then I use it for a specific Model attribute like this:
@Html.DropDownListFor(model => model.PARAMETER_REQUIRED, (SelectList)ViewBag.YesNo)
This gets the job done but I don't like the ViewBag method because it's pretty tedious to maintain it when switching Views and I don't like having to repeat code. I want to change this up so that I can just use
@Html.EditorFor(model => model.PARAMETER_REQUIRED)
and have Razor know that I want this to be a DropDown with my Yes/No attributes.I also want to have this be reusable so that I can use the same template for any fields (in other models) that I want to edit with this Yes/No dropdown.
Is this possible? I know that 'templating' DisplayFor is possible. Can we achieve something similar with EditorFor?