简体   繁体   中英

Can't bind model to Controller, MVC3

I have 2 Views and 1 EditorTemplate

The first view is the Cart.cshtml view and this view has a Model (CartModel) Inside of this view there is a call to the second view using:

@Html.Partial("OrderSummary", Model.CartSummaryModel)

Inside of the OrderSummary.cshtml view I have this

@Html.EditorFor(m => m.OrderItems)

And inside the EditorTemplate (called OrderItemModel) I have

@Html.DropDownListFor(m => m.SelectedQuantity, Model.QuantityList)

The problem is when causing a post on the top most view (Cart.cshtml) the model isn't binding in the controller the "CartSummaryModel" is null. When swapping to a FormCollection there are 2 keys which are:

OrderItems[0].SelectedQuantity
OrderItems[1].SelectedQuantity

How do I bind the form collection data to the Controller's action method?

It's because of the partial:

@Html.Partial("OrderSummary", Model.CartSummaryModel)

Here you are loosing the CartSummaryModel prefix that is required in your input field names. So instead of using partials use editor templates.

Go ahead and move this OrderSummary.cshtml to EditorTemplates/OrderSummary.cshtml and then inside your view replace:

@Html.Partial("OrderSummary", Model.CartSummaryModel)

with:

@Html.EditorFor(x => x.CartSummaryModel, "OrderSummary")

and if the type of the CartSummaryModel property is OrderSummary you don't even need to specify the name of the editor template as ASP.NET MVC will find it by convention:

@Html.EditorFor(x => x.CartSummaryModel)

Now you are good to go and you will see the correct keys sent to the server:

CartSummaryModel.OrderItems[0].SelectedQuantity
CartSummaryModel.OrderItems[1].SelectedQuantity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM