简体   繁体   中英

Templating Html.EditorFor for specific datatype in ASP.Net MVC3?

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?

Here are some really good examples of the built-in display templates and editor templates. Take a look at EditorTemplates/Boolean.ascx. You'll want something like this, in fact I'm not sure why you can't use the Boolean template as-is and change your view model to just be List or other suitable collection. Then, if necessary, you can customize the Boolean editor template to give you the exact DropDownList view you need.

An edit template uses the view assigned to it by the type given; what you may want to do is create a named template and apply the name to the Html.EditorFor overload . Then, you can create a specialized template for that scenario, and not have it be globally defined for the char type. Check out this example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM