1

I totally get the MVC Scaffolding, and the CRUD operation. This is however the case for only one table (model). If I have to update more than one table from the same page, how would I do this? Suppose I need to update Table1, Table2, and Table3. Following I have my code:

Model:

 public class MultipleTableModel
{

    public List<Database.Table1> Table1 { get; set; }
    public List<Database.Table2> Table2 { get; set; }
    public List<Database.Table3> Table3 { get; set; }      
}

(I have intentionally left out the Models for individual tables as that's not relevant and/or important here. CRUD operation for one model is plain and simple.)

Now in my view page, instead of using just one model, I am using this MultipleTableModel so I can make change in all three tables from the same form.

View:

@model MyApp.Models.MultipleTableModel

@using(Html.BeingForm("Action", "Controller", FormMethod.Post)) {
  @foreach (var t1 in Model.Table1)
    {
        *Some code binding values of Table 1 to html elements

    }
}

And similarly I repeat the foreach loop for Table2 and Table3. In the end the submit button submits the whole form to its controller. The way I am trying to receive these values in the controller is as follows:

    [HttpPost]
    public ActionResult Edit(Table1 t1, Table2 t2, Table3 t3)
    {
        *code to maniupate t1, t2, t3*
        return View();
    }

Or I could even try:

    [HttpPost]
    public ActionResult Edit(MultipleTableModel allTables)
    {
        *code to maniupate allTables*
        return View();
    }

First method didn't work for me, returned all null. I haven't tried the second method it's just an idea not sure if it works.

My question is, is it even possible to do what I'm trying? Implement CRUD operations for multiples models form the same page by making a new model(MultipleTableModel) that consists of all other models(Table1, Table2, and so on). Or is there any other (better, easier) way of doing it?

Thanks.

Bivo Kasaju
  • 1,143
  • 3
  • 13
  • 28
  • by "returned all null" do you mean that t1, t2, and t3 were all null? – Sam I am says Reinstate Monica Sep 16 '16 at 16:07
  • @SamIam yes t1 t2 and t3 were all null – Bivo Kasaju Sep 16 '16 at 16:08
  • You cannot use a `foreach` loop to generate form controls for items i a collection. You need to use `for` loops or a custom `EditorTemplate` for each type. Refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) for an explanation. And the POST method needs to be `public ActionResult Edit(MultipleTableModel allTables)` In any case, if your editing data do not use data models. Create view models for each type so that your parent view model contains properties `public List Table1 { get; set; }` etc –  Sep 16 '16 at 22:15

0 Answers0