I'm currently working on a app which is being developed using C# and Asp.Net MVC.
On one of the views I have around 10 DropDowns
which users must select. The selected value is stored into the database.
For Example:
DropDown
hasValue
of1
andText
appears asFirst Main Fault
DropDown
hasValue
ofOne
andText
appears asFirst Sub Fault
Now users can come back and edit their records. So I want to show them the DropDown
which is already selected with the value of what's stored in the database.
For this I make use of the following extension method
public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> items, Func<T, string> textSelector, Func<T, string> valueSelector, Func<T, bool> selecter)
{
return items.OrderBy(item => textSelector(item))
.Select(item =>
new SelectListItem
{
Selected = selecter(item),
Text = textSelector(item),
Value = valueSelector(item)
});
}
Which I call as
var mainFaultSelectedDdl = mainFaults.ToSelectListItems(
m => m.MainFaultDescription,
m => m.Id.ToString(),
m => m.Id == mainFaultId); //mainFaultId here equals to 1. I've also tried m.Id.ToString() == mainFaultId.ToString() but still the same issue
var subFaultSelectedDdl = subFaults.ToSelectListItems(
s => s.SubFaultDescription,
s => s.SubFaultDescription,
s => s.SubFaultDescription == erst.SubFault); //erst.SubFault here equals to One
When I debug my code I can see both of the above DropDowns
Selected
is set to True
but in the view The MainFault DropDown
doesn't be selected but the SubFault DropDown
is selected.
Can someone tell me where I'm going wrong please.
This is how I'm currently generating the DropDown
in the view
@Html.DropDownListFor(m => m.Serial.MainFault, Model.MainFaultDdl, "Please select a main fault", new { id = "mainFaults", @class = "form-control main-ddl" })
@Html.DropDownListFor(m => m.Serial.SubFault, Model.SubFaultDdl, "Please select a sub fault", new { id = "subFaults", @class = "form-control main-ddl" })