.NET MVC - Submitting multiple models of the same type at once

前端 未结 1 1886
北荒
北荒 2021-02-06 15:25

I think I\'ve got a pretty simple scenario but can\'t seem to grasp how to do it in .NET\'s MVC framework. At its simplest, this is a form that has people with a ranking. I\'d

1条回答
  •  一整个雨季
    2021-02-06 15:49

    I did a quick example using a Customer object, but I think it's similar. Note how the form fields are labeled. Prefixed with name of parameter in action in controller. Index is needed to treat as a collection. Yours might be slightly more complex, because you have a nested class. (Person inside of ballot). I think by doing customers[@counter].Person.Id for form fields would work though. Sorry I didn't have an example with ballots. :)

    This would be the relevant part of the View:

    @using (Html.BeginForm())
    {
        var counter = 0;
        foreach (var customer in this.Model)
         {
             
             
             counter++;
         }
         
    }
    

    and this would be the relevant part of the controller:

    public ActionResult Test()
    {
        return View(Service.GetCustomers());
    }
    
    [HttpPost]
    public ActionResult Test(Customer[] customers )
    {
        return View(customers);
    }
    

    0 讨论(0)
提交回复
热议问题