10

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!

3 Answers 3

22

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.

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

1 Comment

Thanks @WheretheresaWill. OMG! I did't realize that overload. Stupid me.
4

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);

Comments

0

You can also create an Helper class for Dropdownlist It will have a method to set the text as by default text for every dropdownlist in you solution

1 Comment

Thanks @K2_Ketu but as WheretheresaWill said, there is a overload which includes this option.

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.