Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set dropdown item selected MVC

I have multiple dropdown list for same select list in look and want to set dropdown item selected as per loop.

How can I set specific one item of dropdown list selected in mvc dropdownlist.

Please help.

like image 294
k-s Avatar asked Mar 21 '12 16:03

k-s


People also ask

How do I set SelectListItem selected?

The SelectListItem class has Text , Value and Selected properties. The first two of these are strings, and the Selected` property is a boolean. You can project data from an Entity Framework context to a collection of SelectListItem like this: public List<SelectListItem> Options { get; set; }

How can set the selected value of dropdown in .NET core?

Click the DropDownList element and select an item from the options list. The selected item's value and text property values will be shown the in property panel. The DropDownList component contains a list of predefined values from that the user can choose a single value.


2 Answers

The Html.DropDownList method takes multiple parameters, one of them being a List<SelectListItem>. The individual instance of the SelectListItem is where you set the Selected property:

var item = new SelectListItem() {

    Selected = /* condition */,

    Value = "Some Value",
    Text = "Some Text"
};

Alternatively:

Create a SelectList collection that exposes the SelectedValue property:

Model.YourSelectList = new SelectList(items /* List<SelectListItem> */,
                                      "Value",
                                      "Text",
                                      37 /* selected value */);
like image 164
Alex Avatar answered Nov 13 '22 11:11

Alex


When building the SelectList, you can set the selected item on construction using http://msdn.microsoft.com/en-us/library/dd460123.aspx

Or you can set it on an individual SelectListItem via it's Selected property ( http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.selected.aspx ) and use the single-parameter constructor of the select list, or pass it straight to the DropDownList method.

like image 42
Andras Zoltan Avatar answered Nov 13 '22 09:11

Andras Zoltan