简体   繁体   中英

Reusing same dropdownlist for multiple fields and populating with db value mvc4

I have the same drop down list for 30 fields on a view. Is there any way to use the same selectlist in the viewbag for all 30 with the default value or do I have to have 30 separate viewbag items with the same select list and default value?

I add the selectlist to the viewbag in my contoller edit method:

ViewBag.Pulmonary_01 = new SelectList(PulmonaryList(), "Text", "Value", admission.Pulmonary_01);

The fields are Pulmonary_01 through Pulmonary_30. In my view I use:

@Html.DropDownList("Pulmonary_01", String.Empty)

If I use ViewBag.Pulmonary instead of the _01 it doesn't match it on save. Two obstacles are matching a general "Pulmonary" view and to all the fields so they save and the other is having the selected value. I don't see a way to avoid having 30 ViewBags.

This is not a problem at all. You can use the same view bag as many times as you want, you just have to cast the ViewBag into a SelectList. So for example if you have a model like:

public class Pulmonary
{
    public int Pulmonary_01 { get; set; }
    public int Pulmonary_02 { get; set; }
    public int Pulmonary_03 { get; set; }

and in your action you create a viewbag like this:

 ViewBag.Pulmonaries = new SelectList(PulmonaryList(), "Text", "Value");

you should be able to do the following in the view:

 @model PulmonaryClassFullNamespace.Pulmonary
 // Form declaration
 @HtmlDropDownListFor(model => Model.Pulmonary_01, (SelectList)ViewBag.Pulmonaries)
 @HtmlDropDownListFor(model => Model.Pulmonary_02, (SelectList)ViewBag.Pulmonaries)
 //.....
 // Form closure

The only thing you really have to watch is that ViewBag property name does not match any model property names. For example if you name your ViewBag.Pulmonary_01 and you have a model property called Pulmonary_01 then this will cause mapping issues because these values will be overwriting each other in form collection.

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