Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a default selected value in DropDownList in MVC3

In MVC3 I have this code at my controller. It retrieves a List of IDs\Names from Installation table and creates a ViewBag

var vs = dba.Installation.OrderBy(q => q.InstName).ToList();
ViewBag.Vessels = new SelectList(vs, "InstId", "InstName");

Now, at my view. I want to render the list in a dropdown list. I used the Html helper that works fine...

@Html.DropDownList("InstId",(SelectList)ViewBag.Vessels, "- Select one -")

I need to set first item in the ViewBag List as a default selected value, instead of "- Select one -" text.

How can I do it?

Thanks in advance!

like image 489
ɐsɹǝʌ ǝɔıʌ Avatar asked Apr 30 '13 11:04

ɐsɹǝʌ ǝɔıʌ


2 Answers

There's an overload for the SelectList constructor that takes 4 arguments. The last of which is the default selected object. E.g:

ViewBag.Vessels = new SelectList(vs, "InstId", "InstName", selectedValue);

Where selectedValue is an object of whatever type is in your list.

like image 73
WheretheresaWill Avatar answered Nov 16 '22 04:11

WheretheresaWill


I need to set first item in the ViewBag List as a default selected value, instead of "- Select one -" text.

Then you need to select the first item in your list (vs) and get it's id and use it as the selecedValue in the SelectList:

ViewBag.Vessels = new SelectList(vs, "InstId", "InstName", 
    vs.FirstOrDefault().InstId);
like image 43
von v. Avatar answered Nov 16 '22 03:11

von v.