c# - MVCCheckBoxList catering for a 1 to Many relationship -
i have class has 1 many relationship class. use class car , class gears. need create form, registers car , user needs specify choice of gears.
public class car { public int id { get; set; } public string desc { get; set; } public list<gear> gears { get; set; } } public class gear { public int gid { get; set; } public int gname { get; set; } }
using asp.net mvc 5, have create form, have scaffolded car model, , within form, wish have checkboxlist of gears,
i have viewmodel have provided checkboxlist below:
public class gearsviewmodel { public gear _gear {get; set; } public bool _ischecked {get; set;} }
controller looks like:
gears fetched db context "gearr","gear1","gear2","gear3","gear4","gear5","gear6","gear7"
public action create() { viewbag.gears = new selectlist(db.gears, "gid","gname"); list<gearviewmodel> _gears= new list<gearviewmodel>(); foreach(gear g in viewbag.gears) { _gears.add(new gearviewmodel(g, false)); } viewbag.gearschecklist = _gears.tolist(); return view(); }
now, part i'm getting stuck at, how display , capture details in createview.
i need assistance on how design create form , how capture info.
firstly, view models should not contain data models when editing. view models should (add validation , display attributes appropriate)
public class carvm { public int? id { get; set; } public string description { get; set; } public list<gearvm> gears { get; set; } } public class gearvm { public int id { get; set; } public string name { get; set; } public bool isselected { get; set; } }
and method be
public actionresult create() { var gears = db.gears; carvm model = new carvm { gears = gears.select(x => new gearvm { id = x.gid, name = x.gname }).tolist() }; return view(model); }
and view be
@model carvm .... @using (html.beginform()) { ..... // elements editing id , description properties of carvm @for (int = ; < model.gears.count; i++) { <div> @html.hiddenfor(m => m.gears[i].id) @html.hiddenfor(m => m.gears[i].name) // include if want in post method @html.checkboxfor(m => m.gears[i].isselected) @html.labelfor(m => m.gears.isselected, model.gears[i].name) </div> } <input type="submit" .... /> }
then in post method
public actionresult create(carvm model) { if (!modelstate.isvalid) { return view(model); } // id's of selected gears ienumerable<int> selected = model.gears.where(x => x.isselected).select(x => x.id); // initialize data models, save , redirect }
Comments
Post a Comment