Skip to content Skip to sidebar Skip to footer

Bind Dropdownlistfor With List On Viewmodel

I'm trying to do this: This is my ViewModel and Model: public class OpeningYearViewModel { public int OpeningYearId { get; set; } public string Description { get; set; }

Solution 1:

I can't understand why this is happening but you can workaround it by setting explicitly the selected value. This can be done by passing Model.GradesList[i].CurrencyId as fourth parameter to the SelectList's constructor:

@for(int i = 0; i < Model.GradesList.Count; i++)
{
    @Html.DropDownListFor(x => x.GradesList[i].CurrencyId, 
        new SelectList(ViewBag.currencyList, "Value", "Text", Model.GradesList[i].CurrencyId))
}

Solution 2:

Since, the DropDownListFor is used in loop to generate indexed inputs; so generate input controls will be generated with name as "GradeList[0].CurrencyId", "GradeList[1].CurrencyId"......Due to this framework will not bind the selected value in Select List as it is unable to get the value in reflection for selection. That's why you have to use the following SelectList constructor to set the selected value.

publicSelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    object selectedValue
)

However, if your DropDownListFor is bind to a simple expression like

@Html.DropDownListFor(model => model.CurrencyId, new SelectList(ViewBag.Items, "Value", "Text"))

then selection will work automatically.

Post a Comment for "Bind Dropdownlistfor With List On Viewmodel"