Reputation: 21
I want to set a selected value in my select list by default.
Here I have this select list :
@{
List
<SelectListItem>
dateEcheancierCc = new List
<SelectListItem>
();
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
}
<div class="md-select px-0" style="min-width:0px">
@Html.DropDownList("DateEche", dateEcheancierCc, new { @class = "form-conrol" })
</div>
}
Here I'am trying to set "Selected-value-by-default" is selected by default but it is not working for me why ?
Here the Dropdownlist:
@Html.DropDownList("DateEche", dateEcheancierCc, new { @class = "form-conrol" })
Upvotes: 0
Views: 6219
Reputation: 67
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
change to like this
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
make sure the item that you set "Selected = true" is the only one in list
I don't know your rule but you can try like this
for example : I have an array { "Jeffrey", "John", "Joe", "Josh" }, and I want set Jeffrey as default selected
if (dateEch == "Jeffrey")
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
else
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch });
Upvotes: 1
Reputation: 186
Replace your DropdownList as below,
<div class="md-select px-0" style="min-width:0px">
@Html.DropDownList("DateEche",new SelectList(dateEcheancierCc,"Value","Text","Selected-value-by-default"), new { @class = "form-conrol" })
</div>
and selectList as
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(
new SelectListItem() { Text = dateEch, Value = dateEch }
);
}
https://dotnetfiddle.net/RFgoD1
Upvotes: 0
Reputation: 61
You need to add Selected=true
while building the SelectListItem
.
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch ,Selected = true });
}
Upvotes: 0
Reputation: 11
if your views have model then you can use like this
@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.SelectCollections, "Value", "Text", Model.ValueToBeSelectedInCollection))
Upvotes: 0