我在过去的几周里一直在快速学习MVC 3,但有些东西出现了,我只是无法解决搜索几个小时的问题。我正在开发一个简单的购物车,并试图通过结账过程以线性路径传递数据。无论我尝试什么,我都无法将模型传递给下一个视图。POST模型到控制器方法
首先,使用IModelBinder的实现从会话中拉取'Cart'实体。它基本上可用于任何方法。它一直在努力工作一段时间。我的问题是试图在/ cart/confirm和/ cart/checkout之间传递相同的模型。
有人可以帮助弄清楚为什么模型总是空的控制器/购物车/结帐?
public class CartController : Controller
{
public ActionResult Index (Cart cart)
{
//Works fine, anonymous access to the cart
return View(cart);
}
[Authorize]
public ActionResult Confirm (Cart cart)
{
//Turn 'Cart' from session (IModelBinder) into a 'Entities.OrderDetail'
OrderDetail orderDetail = new OrderDetail();
orderDetail.SubTotal = cart.ComputeTotalValue();
...
...
return View(orderDetail);
}
[Authorize]
public ActionResult Checkout(OrderDetail model)
{
//PROBLEM: model is always null here.
}
}
/Views/Cart/Index.aspx看起来像这样(对不起,没有剃刀):
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site-1-Panel.Master" Inherits="System.Web.Mvc.ViewPage<My.Namespace.Entities.Cart>" %>
...
...
<% using(Html.BeginForm("confirm", "cart")) { %>
Not much to see here, just a table with the cart line items
<input type="submit" value="Check Out" />
<% } %>
我怀疑问题就在这里,但我试过的HTML每一个变化。 BeginForm()我可以尝试并不能让模型传递到/ cart/checkout。总之,/Views/Cart/Confirm.aspx看起来是这样的:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site-1-Panel.Master" Inherits="System.Web.Mvc.ViewPage<My.Namespace.Entities.OrderDetail>" %>
...
...
<% using (Html.BeginForm("checkout", "cart", Model)) { %>
<%: Model.DBUserDetail.FName %>
<%: Model.DBUserDetail.LName %>
<%: Html.HiddenFor(m => m.DBOrder.ShippingMethod, new { @value = "UPS Ground" })%>
<%: Html.HiddenFor(m => m.DBOrder.ShippingAmount, new { @value = "29.60" })%>
...
...
<input type="submit" value="Confirm & Pay" />
<% } %>
最后/Views/Cart/Checkout.aspx看起来是这样的:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site-1-Panel.Master" Inherits="System.Web.Mvc.ViewPage<My.Namespace.Entities.OrderDetail>" %>
...
...
<%: Html.Hidden("x_first_name", Model.DBUserDetail.FName) %>
<%: Html.Hidden("x_last_name", Model.DBUserDetail.LName) %>
...
It doesn't really matter what's here, an exception gets throw in the controller because the model is always null
你确实教会我一个很好的方式来找到模型错误,它确实使我在正确的方向。这是我试图用作模型的'Entities.OrderDetail'的一个问题。该实体只拥有2个公共对象,都是Linq to SQL对象。也许我不能用它作为模型,不得不使用POCO对象? – CraigKC 2012-03-18 03:27:31