代码之家  ›  专栏  ›  技术社区  ›  Mike

ASP.NET MVC:隐藏表单字段在发布后不接受来自模型的新值

  •  1
  • Mike  · 技术社区  · 15 年前

    在我看来,我目前有以下代码:

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

    当页面最初加载时,cartid为空,因此当我在页面上查看源代码时,值设置为“”。当我在页面上提交表单(添加产品)时,控制器代码将创建一个新的购物车,并使用强类型的ViewModel,我将购物车返回到带有购物车ID的视图中。问题是隐藏表单字段的值不会用新值更新。

    我已经验证了我确实在传递一个在邮件中包含cartid的购物车实例。

    这是一些控制器代码。控制器称为订单,视图称为创建:

    [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 回复  |  直到 11 年前
        1
  •  3
  •   Dan Atkinson    13 年前

    我通过创建新的 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()));
      }
    }