tags:

views:

243

answers:

1

In my view I currently have the following code:

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

When the page initially loads, CartID is null so when I view source on the page the value is set to "". When I submit the form on the page (adding a product), the controller code will create a new cart and using a strongly typed viewmodel, I pass the cart back into the view with a CartID. The problem is that the value for the hidden form field doesn't get updated with the new value.

I have verified that I am indeed passing back a Cart instance complete with CartID on the post.

Here is some of the controller code. The controller is called Orders and the view is called 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);
            }

Has anyone experienced this issue before? How do I go about fixing it?

Thanks!

A: 

I fixed this by creating a new Html.Hidden extension which basically overrode what the default one did.

Quick example below.

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}\" />", name, value.ToString());
  }
}
Dan Atkinson