2010-01-13 82 views
1

在我看來,後受理的模式新價值目前,我有以下代碼:ASP.NET MVC:隱藏的表單字段不交

<%= Html.Hidden("Cart.CartID", Model.Cart.CartID) %> 

當頁面最初加載,CartID爲空,所以當我查看源代碼在頁面上將值設置爲「」。當我在頁面上提交表單(添加產品)時,控制器代碼將創建新購物車並使用強類型視圖模型,然後使用CartID將購物車返回到視圖中。問題是隱藏表單字段的值不會使用新值更新。

我已經驗證過,我確實在帖子後面傳遞了一個帶有CartID的Cart實例。

以下是一些控制器代碼。該控制器被稱爲訂單和視圖被稱爲創建:

[AcceptVerbs(HttpVerbs.Post)] 
[MultiButton(MatchFormKey = "action", MatchFormValue = "AddProduct")] 
public ActionResult Create(Product product, Cart cart, Customer customer) 
{ 
    if (cart.CartID == null) 
    { 
     Guid _cartIdentifier; 
     _cartIdentifier = Guid.NewGuid(); 
     var _newCart = new Cart() { CartIdentifier = _cartIdentifier, CartDate = DateTime.Now }; 
     cart = _cartRepository.Add(_newCart); 
    } 

    var _cartItem = new CartItem() { CartID = cart.CartID, ProductID = Convert.ToInt32(product.ProductID) }; 
    _cartRepository.Add(_cartItem); 

    var _cartItems = _cartRepository.GetCartItems(new CartItem() { CartID = cart.CartID }); 

    var viewState = new GenericViewState 
    { 
     Cart = cart, 
     CartItems = _cartItems 
    };   

    return View(viewState); 
} 

有沒有人遇到過這個問題?我該如何解決它?

謝謝!

+1

我們可以看到一些控制器嗎? – 2010-01-13 18:10:10

+0

用控制器代碼更新了文章。 – Mike 2010-01-13 18:30:58

+0

'GenericViewState'看起來像什麼? – 2010-01-13 18:31:00

回答

3

我通過創建一個新的Html.Hidden擴展來解決這個問題,它基本上覆蓋了默認的擴展。

快速示例如下。

public static class HtmlHelpers 
{ 
    public static string Hidden(this HtmlHelper helper, string name, object value) 
    { 
    return string.Format("<input type=\"hidden\" name=\"{0}\" value=\"{1}\" />", helper.Encode(name), helper.Encode(value.ToString())); 
    } 
} 
+0

@usr:你可以簡單地修改我的答案來編碼! – 2012-02-14 10:56:31