Linking an array to multiple DropDownListFor

I have a scenario where I want to select 3 items from a list of checkboxes. This works great, but if the checkbox list is long, the page looks unwieldy. So I wanted to change it to 3 dropdowns. so the page was much smaller, but none of the dropdowns rated the selected value.

So I tried code like this

@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 0 ? Model.CheckedLarcenyTypes[0] : null as Int32?), String.Empty, new { id = "Larceny1" })
@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 1 ? Model.CheckedLarcenyTypes[1] : null as Int32?), String.Empty, new { id = "Larceny2" })
@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 2 ? Model.CheckedLarcenyTypes[2] : null as Int32?), String.Empty, new { id = "Larceny3" })

      

Now the dropdowns are rendered correctly and the correct value is getting bound, and on POST I see the values ​​being sent back to the view models.

I just can't get the selectvalue in the dropdown. dropdowns remain empty when the page is reloaded.

What am I doing wrong here? Is it possible?

+3


source to share


1 answer


Your problem is related to what is described here .

Read selection

If you are using the same model to receive input from the edit view during postback, you might think that the default binder will re-populate the album collection with all the album information and set the selected album. Unfortunately - the network does not work this way and the album collection will be empty.

So, you should have a ViewModel:

public class LarcenyViewModel
{
    public int CheckedLarcenyType1 { get; set; }
    public int CheckedLarcenyType2 { get; set; }
    public int CheckedLarcenyType3 { get; set; }             
    public IEnumerable<SelectListItem> LarcenyTypes { get; set; }
}

      



Set up your ViewModel like this:

LarcenyViewModel larcenyViewModel = new LarcenyViewModel();

// Use a database, enum or whatever to get the LarcenyTypes... :)
larcenyViewModel.LarcenyTypes = new SelectList(
               database.FindAllLarcenyTypes(), "LarcenyId", "Name");

      

View code:

@Html.DropDownListFor(model => model.CheckedLarcenyType1, Model.LarcenyTypes, String.Empty, new { id = "Larceny1" })
@Html.DropDownListFor(model => model.CheckedLarcenyType2, Model.LarcenyTypes, String.Empty, new { id = "Larceny2" })
@Html.DropDownListFor(model => model.CheckedLarcenyType3, Model.LarcenyTypes, String.Empty, new { id = "Larceny3" })

      

+2


source







All Articles