c# - Creating multiple models in ASP.Net MVC -
i using code-first ef. simplified version of models:
public class person { public int personid { get; set; } public string name { get; set; } public list<phone> phones { get; set; } } public class phone { public int phoneid { get; set; } public string number { get; set; } public virtual person person{ get; set; } public int personid { get; set; } } so have 1 many relationship between person , phone.
i enable user add many phones possible in create view person. when form in view submitted, save both person , of phones added.
can point me in right direction? read editor-for templates, proper use case?
you can use viewmodel this
public class personaddviewmodel { public string name{set;get;} public list<string> phones{set;get;} } on form of view can add code
@using (html.beginform("add", "person", formmethod.post })) { <div class="col-md-6"> <div class="form-group"> @html.labelfor(p => p.name) @html.editorfor(p => p.name, new { @class = "form-control" }) </div> </div> <div class="col-md-6" id="#row-0"> <div class="form-group"> @html.labelfor(p => p.phones[0]) @html.editorfor(p => p.phones[0], new { @class = "form-control" }) </div> </div> <div id=otherphones></div> <button type="button" class="btn btn-danger btn-float btn-float-lg btn- rounded" id="add"><i class="icon-plus2"></i></button> <button type=submit>submit</button> } then add jquery script page
$("#add").click(function () { inputcount++; var newdiv = $("#row-0").clone(); newdiv.attr('id', 'row-' + inputcount); newdiv.find("input,select").each(function () { $(this).attr({ 'name': function (_, name) { return name.tostring().replace('0', inputcount) }, 'id': function (_, id) { return id.tostring().replace('0', inputcount) }, 'item': function (_, item) { return item.tostring().replace('0', inputcount) } }); var type = $(this).attr('type'); if (type === 'hidden') { $(this).val('0'); } else { $(this).val(''); } }); newdiv.find(".available").each(function () { $(this).attr({ 'id': function (_, id) { return id.tostring().replace('0', inputcount) } }); }); newdiv.find(".delcol").each(function () { $(this).find('button').attr('item', inputcount); $(this).fadein(); }); newdiv.find("label").each(function () { $(this).attr({ 'for': function (_, id) { return id.tostring().replace('0', inputcount) } }); }); newdiv.find(".field-validation-valid").each(function () { $(this).attr({ 'data-valmsg-for': function (_, id) { return id.tostring().replace('0', inputcount) } }); }).end(); $("#other").append(newdiv); $('form').data('validator', null); $.validator.unobtrusive.parse('form'); });
Comments
Post a Comment