Muhammad Ashikuzzaman
Muhammad Ashikuzzaman

Reputation: 3153

Creating multiple Dropdownlist from one Viewbag select list

In controller:

 DbModel db = new DbModel();
 ViewBag.SUBJECT_NO = new SelectList(db.SUBJECT, "SUBJECT_NO", "SUBJECT_NAME"); 

The default code for making DropDownList from this viewbag is:

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

But in view I want to create three select list from this one viewbag. Such that one teacher is experienced in three subject from the subject list. But each DropDownList name will not be the default Viewbag name "SUBJECT_NO". It will be

"SUBJECT_NO1", "SUBJECT_NO2" , "SUBJECT_NO3".

and in DbModel the teacher class will have three column with these names. I don't want to create so many viewbag against one DbModel table. There will be 5 different options for subject in this view and action. And for that I have to create 5*3=15 viwbag for 5 DbModel classes. I want to this with only 5 Viewbags.

I will really appreciate him who can help me.

Upvotes: 0

Views: 1408

Answers (1)

JamieD77
JamieD77

Reputation: 13949

@Html.DropDownList() has 8 overrides. You just need to find the one that allows you to define the source.

Like

@Html.DropDownList("SUBJECT_NO1", (SelectList)ViewBag.SUBJECT_NO, string.Empty, null)
@Html.DropDownList("SUBJECT_NO2", (SelectList)ViewBag.SUBJECT_NO, string.Empty, null)
@Html.DropDownList("SUBJECT_NO3", (SelectList)ViewBag.SUBJECT_NO, string.Empty, null)

This happens to use the method

public static MvcHtmlString DropDownList(
    this HtmlHelper htmlHelper, 
    string name, 
    IEnumerable<SelectListItem> selectList, 
    string optionLabel, 
    object htmlAttributes
);

Upvotes: 2

Related Questions