【问题标题】:ASP.NET MVC: Hidden form field not accepting new value from model after postASP.NET MVC:隐藏的表单字段在发布后不接受来自模型的新值
【发布时间】:2013-05-15 18:17:49
【问题描述】:

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

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

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

我已经确认我确实在帖子中传回了一个带有 CartID 的 Cart 实例。

这里是一些控制器代码。控制器称为 Orders,视图称为 Create:

[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);
}

以前有人遇到过这个问题吗?我该如何解决它?

谢谢!

【问题讨论】:

  • 我们可以看看你的一些控制器吗?
  • 用控制器代码更新了帖子。
  • GenericViewState 长什么样子?
  • @Mike,是的,看这个:stackoverflow.com/questions/594600/…
  • 丹,就是这样。我使用了常规的 HTML Hidden 字段而不是 helper,它起作用了。谢谢!

标签: asp.net-mvc


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多