asp.net - Binding ICollection to edit form in MVC asp .NET -
i have 2 models: student
, course
. want create simple form edits course information, e.g. name of course, , adds or removes students to/from course. this, course
model has property public virtual icollection<student> students { get; set; }
. create form this:
@using (html.beginform()) { @html.antiforgerytoken() <div class="form-horizontal"> <h4>create course</h4> <hr /> @html.validationsummary(true) @html.hiddenfor(model => model.id) <div class="form-group"> @html.labelfor(model => model.coursename, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @html.editorfor(model => model.coursename) @html.validationmessagefor(model => model.coursename) </div> </div> <div class="form-group"> @html.labelfor(model => model.time, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @html.editorfor(model => model.time) @html.validationmessagefor(model => model.time) </div> </div> <div class="form-group"> @html.labelfor(model => model.students, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @html.listboxfor(model => model.students, (ienumerable<selectlistitem>)viewbag.students) @html.validationmessagefor(model => model.students) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="save" class="btn btn-default" /> </div> </div> </div> }
the form fetches students list without problem. when hit save button , start debugging application, details of course, name , time, passed server, selected students not. not this, when load form, if course has students in it, students not selected in list. can tell me mistake i'm making?
you need create list<int>
in course
model. so, can map it. selected values list box return list<int>
not list<student>
. so, need create viewmodel
if can not edit existing model.
below sample course model or viewmodel.
public class course { public int id { get; set; } public string coursename { get; set; } public string time { get; set; } public list<int> students { get; set; } }
Comments
Post a Comment