1

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.