c# - ASP.Net mvc 5 - Save Parent and child records together -


i getting started asp.net mvc 5 , got stuck 1 problem have explained below:

i have user , history models. , user can have more 1 history.

user model:

public class user {     public int id { get; set; }     public string tickettype { get; set; }     public string firstname { get; set; }     public string lastname { get; set; }     public string gender { get; set; }      public virtual icollection<history> histories { get; set; } } 

history model:

public class history {     public int id { get; set; }     public int year { get; set; }     public int month { get; set; }     public int day { get; set; }      public virtual user user { get; set; } } 

usercontroller:

public class userscontroller : controller {     private mydbcontext db = new mydbcontext();      public actionresult create()     {         var user = new user();         user.histories = new list<history>();         user.histories.add(new history { });         return view();     }      [httppost]     [validateantiforgerytoken]     public actionresult create([bind(include = "id,tickettype,firstname,lastname")] user user)     {         if (modelstate.isvalid)         {             db.users.add(user);             db.savechanges();             return redirecttoaction("index");         }          return view(user);     } } 

here form:

create.cshtml

@model myapp.models.user  @using (html.beginform()) {     @html.antiforgerytoken()      @html.partial("_form")      <input type="submit" value="create" class="btn btn-lg btn-success" /> } 

_form.cshtml: remove duplication in both create , edit forms

        @model myapp.models.user         @html.validationsummary(true, "", new { @class = "text-danger" })          <div class="form-group">             @html.labelfor(model => model.tickettype, htmlattributes: new { @class = "control-label" })             @html.dropdownlistfor(model => model.tickettype, new list<selectlistitem>                     {                         new selectlistitem() {text = "opd", value="opd"},                         new selectlistitem() {text = "emergency", value="emergency"},                     }, htmlattributes: new { @class = "form-control" })             @html.validationmessagefor(model => model.tickettype, "", new { @class = "text-danger" })         </div>          <div class="form-group">             @html.labelfor(model => model.firstname, htmlattributes: new { @class = "control-label" })             @html.editorfor(model => model.firstname, new { htmlattributes = new { @class = "form-control" } })             @html.validationmessagefor(model => model.firstname, "", new { @class = "text-danger" })         </div>          <div class="form-group">             @html.labelfor(model => model.lastname, htmlattributes: new { @class = "control-label" })             @html.editorfor(model => model.lastname, new { htmlattributes = new { @class = "form-control" } })             @html.validationmessagefor(model => model.lastname, "", new { @class = "text-danger" })         </div>           <!-- todo: fix these form elements           related history not user. not sure how that.           note that, user fields saving ,           update working. -->           <div class="form-group">             <label class="control-label">year</label>             <input type="text" value="" class="form-control" />         </div>          <div class="form-group">             <label class="control-label">month</label>             <input type="text" value="" class="form-control" />         </div>          <div class="form-group">             <label class="control-label">day</label>             <input type="text" value="" class="form-control" />         </div> 

you have first created viewmodel. view model combine user , history model below code

public class userviewmodel {       public string tickettype { get; set; }      public string firstname { get; set; }      public string lastname { get; set; }      public string gender { get; set; }               public int year { get; set; }      public int month { get; set; }      public int day { get; set; }   } 

second, chtml view modified :

set model userviewmodel

 @model myapp.models.userviewmodel 

form design change code in year, month , day

  <table>     <thead>         <tr>           <td>year</td>           <td>month</td>           <td>day</td>        </tr>       </thead>       <tbody id="tbodyval">       </tbody>     </table>   <div class="form-group">         <label class="control-label">year</label>         @html.editorfor(model => model.year, new { htmlattributes = new { @class = "form-control" } })  </div>   <div class="form-group">     <label class="control-label">year</label>     @html.editorfor(model => model.month, new { htmlattributes = new { @class = "form-control" } })  </div>   <div class="form-group">     <label class="control-label">year</label>     @html.editorfor(model => model.day, new { htmlattributes = new { @class = "form-control" } })   </div>   <input type="button" value="add"> 

if add button click create new row in table t body every inside textbox or hiddenfield vlaue assied current textbox value

for example jquery function

  $("#add").click(function(){       string row="<tr><td><input type='text' value='$('#year').val(),         name='yearlist'></td>         <td><input type='text' value='$('#month').val(), name='monthlist'></td>        <td><input type='text' value='$('#day').val(), name='daylist'></td>           </tr>"         $("#tbodyval").append(row);     }); 

cahnge code in controller:

[httppost] [validateantiforgerytoken] public actionresult create( userviewmodel usermodel, string[] yearlist,string[] monthlist,string[] daylist()) {     if (modelstate.isvalid)     {          user model=new user()         model.tickettype=.usermodel.tickettype;         model.firstname=usermodel.firstname;         model.lastname=usermodel.lastname;         model.gender=usermodel.gender;         for(int i=0;i<yearlist.count();i++)        {          history child=new history()             child.year=yearlist[i].year;          child.month=montlist[i].month;          chile.day=daylist[i].day;                      model.histories.add(child);          }                                db.users.add(model);         db.savechanges();         return redirecttoaction("index");     }      return view(user); } 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -