Monday, 15 September 2014

asp.net mvc - Binding array to multiple DropDownListFor -



asp.net mvc - Binding array to multiple DropDownListFor -

i have scenario want pick 3 items out of list of checkboxes. works fine, if list of checkboxes gets long, page looks unwieldy. wanted alter 3 dropdown lists. page lot smaller, none of dropdown lists honor selected value.

so tried code this

@html.dropdownlistfor(model => model.checkedlarcenytypes, new selectlist(model.larcenytypes, "key", "value", model.checkedlarcenytypes.length > 0 ? model.checkedlarcenytypes[0] : null 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 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 int32?), string.empty, new { id = "larceny3" })

now dropdowns created correctly , right value getting bound , on post see values getting sent in view model.

i can't selectvalue show in dropdown. upon re-loading page, dropdowns still blank.

what doing wrong here? possible?

your problem related what's described here.

reading selection

if using same model take input edit view during postback, might think default model binder repopulate albums collection album info , set selected album. unfortunately - web doesn’t work way , albums collection empty.

so must have viewmodel this:

public class larcenyviewmodel { public int checkedlarcenytype1 { get; set; } public int checkedlarcenytype2 { get; set; } public int checkedlarcenytype3 { get; set; } public ienumerable<selectlistitem> larcenytypes { get; set; } }

populate viewmodel this:

larcenyviewmodel larcenyviewmodel = new larcenyviewmodel(); // utilize database, enum or whatever 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" })

asp.net-mvc razor model-binding html.dropdownlistfor

No comments:

Post a Comment