0

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.

3
  • 1
    30 drop downs in the same screen. that is terrible for the user. Commented May 30, 2013 at 20:12
  • @Shyju I agree but they have this table they have to fill out and don't see a better way to do it without making more pages. This is a data collection site with a lot of fields they have to input. Commented May 30, 2013 at 20:46
  • Split into wizards ( Next Next Next..) Commented May 30, 2013 at 20:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.