简体   繁体   English

无法将模型绑定到Controller,MVC3

[英]Can't bind model to Controller, MVC3

I have 2 Views and 1 EditorTemplate 我有2个视图和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: 第一个视图是Cart.cshtml视图,并且该视图具有模型(CartModel)。在此视图内,可以使用以下命令调用第二个视图:

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

Inside of the OrderSummary.cshtml view I have this 在OrderSummary.cshtml视图内部,我有这个

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

And inside the EditorTemplate (called OrderItemModel) I have 在EditorTemplate(称为OrderItemModel)内部,

@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. 问题是,当在最高视图(Cart.cshtml)上发布帖子时,模型未在控制器中绑定,因此“ CartSummaryModel”为null。 When swapping to a FormCollection there are 2 keys which are: 交换到FormCollection时,有两个键:

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

How do I bind the form collection data to the Controller's action method? 如何将表单收集数据绑定到Controller的action方法?

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. 在这里,您失去了输入字段名称中所需的CartSummaryModel前缀。 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: 继续并将此OrderSummary.cshtml移动到EditorTemplates/OrderSummary.cshtml ,然后在视图内部替换:

@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: 如果类型CartSummaryModel属性是OrderSummary你甚至不需要指定编辑模板的名称为ASP.NET MVC将按照约定找到它:

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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