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.
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; }
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.
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 */);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With