I am trying to create a form in C# ASP.NET 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 models:
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 method:
[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