简体   繁体   中英

How to save views input data into different tables?

I'm an ASP.NET MVC beginner and currently I use EF with a database-first approach to do my work. Everything goes well and every model have its controller and views files. I face problem when I want to save multi model data on a view.

In my case:

  1. I have ASP.NET MVC form for teacher details data, and another for teacher employment history (this two are auto generate from scaffolding database approach)
  2. I want a view Create.cshtml where user inputs teacher details and employment history and this can be saved into their own tables. Therefore, I use tuple and follow what ( Multiple models in a view ) and ( Two models in one view in ASP MVC 3 ) did. As a result, I successfully create teacher details and employment history on a view (Just interface).
  3. But I have no idea how to save the input into the different tables (2 tables: teacher , employmentHistory ). Now, when I save the input, nothing happens.

I guess I need to do something on controllers parts, please give me some ideas on how to do it.

Thanks in advance

First, welcome to StackOverflow!

You are correct, you should do something on the controller part.

  1. I would create a ViewModel for the view. By doing this you can project the data from the database in any way that is needed in the view. Also, with this approach you don't return the full entity, maybe there is some sensitive information there. And you can get the benefit of the model validations also. (For example, what if at some point you need to add another field from another entity?)
  2. I would also create partial views for the information in the view model and pass that model to the partial view, this way enabling the re-use of the views, if needed.
  3. When passing the data to the controller you can pass the ViewModel and then save the data in the database.

Since you didn't give no model info of your classes, I give below an example. Either way (view model or tuple example you followed), you should change the controller code similar to what I'm writing below.

public class TeacherViewModel
 {
    //teacher details
    [Required]
    public int TeacherId {get; set;}
    [Required]
    public string TeacherName {get; set;}
    // {...}
    //teacher employment info
    //here you can have a list of information or the last entry in the history, 
    //or what's required to add a new entry
    public string LastWorkPlace {get; set;}
    public DateTime From {get; set;}
    public To {get; set; }
    //{...}
 }


public class TeacherController: Controller
{
     //{...}
     [HttpPost]        
     public ActionResult SaveTeacherInfo(TeacherViewModel model){
          if (ModelState.IsValid) {
              var teacher = new TeacherEntity 
              {
                 TeacherId = model.TeacherId, //if update otherwise leave blank
                 TeacherName = model.TeacherName
                 //{...}
              };
              //your context name here
              _dbContext.Teachers.Add(teacher);
              var teacherEmploymentInfo = new TeacherEmploymentHistory
              {
                 TeacherId = teacher.TeacherId,
                 LastWorkPlace = model.LastWorkPlace,
                 From = model.From,
                 To = model.To
                 //{...}
              };
              _dbContext.TeachersEmploymentInfo.Add(teacherEmploymentInfo);
              _dbContext.SaveChanges();
             //_dbContext.SaveChangesAsync(); if using async await
          }
          return View(model); //return any validation errors from the view model 
          // to the user to fix.
     }
}

If you are using the ErrorHandler as a global filter no need for try..catch block if you are not planing to return custom errors (BusinessException or DatabaseException, for example) from the controller, if not, you should wrap the code in a try..catch block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM