I am trying to create a form in C# MVC for a practice restaurant app with model binding. I am having a bit of a difficult time comprehending what it is exactly that I am doing wrong or how to do it. I have a form of OrderItems and a quantity. I want to make models with the quantities so that I can make the corresponding order rows in the database.
The Form (It is a Partial View):
@using FormAddOrderItemModel = Restaurant.Models.Order.Form.FormAddOrderItemModel
@model FormAddOrderItemModel;
@using (Html.BeginForm("Form_AddOrderItems", "Order", FormMethod.Post))
{
for (var i = 0; i < Model.OrderItems.Count; i )
{
var item = Model.OrderItems[i];
<div>
@Html.Label(item.Name)
@Html.HiddenFor(m => m.ContentsList[i].OrderItem, item)
@Html.LabelFor(m => m.ContentsList[i].Quantity)
@Html.TextBoxFor(m => m.ContentsList[i].Quantity)
</div>
}
<input class="btn btn-primary" type="submit" value="Submit">
}
The Model:
using System.Collections.Generic;
namespace Restaurant.Models.Order.Form
{
public class FormAddOrderItemModel
{
public List<OrderItem> OrderItems { get; set; }
public List<FormContents> ContentsList { get; set; }
}
public class FormContents
{
public OrderItem OrderItem { get; set; }
public int Quantity { get; set; }
}
}
The Controller Action:
[HttpPost]
public IActionResult Form_AddOrderItems(List<FormContents> response) {
var test = response;
return View("ManageOrder", _orderService.PrepareManageOrderViewModel(12));
}
I was under the assumption that this would populate a list of FormContents. The 'response' in the Controller Action is an instantiated List of FormContents with a count of 0.
How can I pass a List of FormContents from my Partial View to my Controller?
CodePudding user response:
since you are submitting a form , the input parameter of the action should be the same as the form model
public IActionResult Form_AddOrderItems(FormAddOrderItemModel model)
and your view model can be simplier
@model Restaurant.Models.Order.Form.FormAddOrderItemModel