我在過去的幾周裏一直在快速學習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