Change Selected = true in SelectedListItem in ASP.NET MVC3 View by condition
-
13-06-2021 - |
Question
This is my Model:
public class MyModel{
public string Name { get; set; }
public string listType { get; set; }
public string SelectedItem { get; set; }
}
I have a partial view:
@model List<MyModel>
@{
SelectListItem iEqualTo = new SelectListItem { Text = "Equel To", Value = "EqualTo" };
SelectListItem iNotEqualTo = new SelectListItem { Text = "Not Equal To", Value = "NotEqualTo" };
SelectListItem iGreaterThan = new SelectListItem { Text = "Greater Than", Value = "GreaterThan" };
SelectListItem iLessThan = new SelectListItem { Text = "Less Than", Value = "LessThan" };
SelectListItem iBetween = new SelectListItem { Text = "Between", Value = "Between" };
List<SelectListItem> MyFirstList = new List<SelectListItem>() {
iEqualTo, iNotEqualTo, iGreaterThan, iLessThan, iBetween
};
List<SelectListItem> MySecondList = new List<SelectListItem>() {
iEqualTo, iNotEqualTo
};
}
@foreach(var item in Model) {
if(item.listType =="Firsttype"){
<span> @Html.DropDownList(item.Name , MyFirstList) </span>
} else {
<span> @Html.DropDownList(item.Name , MySecondList) </span>
}
}
So I need Selected = true
in List<SelectListItem>
in DropDownList
that item which name equal to MyModel.SelectedItem
? what is your suggestion? In actual my view have more SelectListItem
and List<SelectListItem>
and for some limitations I can't pass the List<SelectListItem>
as my model property and I need to handle it in view. I think to handle it by lambda inline but I don't know is possible, something like this: @Html.DropDownList(item.Name , MySecondList.each(a=> if (a.ToString() == item.SelectedItem) {a.Selected = true})
Is any way to do this? and if I am wrong to use inline lambda does any other way to handle this?
Solution
You can use a SelectList, which has a constructor with an IEnumerable and an Object (selected value).
@Html.DropDownList(item.Name, new SelectList(MyFirstList, item.SelectedItem));
EDIT
I think I faced your problem when trying to use a DropDownList in a loop.
You can try to use this generic extension method (in a static "helper" class)
public static IEnumerable<SelectListItem> ToSelectListItem<T, TValue, TText, TSelectedValue>(this IEnumerable<T> enumerable,
Func<T, TText> text,
Func<T, TValue> value,
TSelectedValue selectedValue)
{
return enumerable.Select(item => new SelectListItem
{
Text = text(item).ToString(),
Value = value(item).ToString(),
Selected = value(item).Equals(selectedValue)
}).AsEnumerable();
}
and then
@Html.DropDownList(item.Name, MyFirstList.ToSelectListItem(m => m.Text, m => m.Value, item.SelectedItem)