Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Saied 349 posts 674 karma points
    Sep 18, 2015 @ 19:49
    Saied
    0

    UmbracoContext.Current.PageId is null when calling @Url.Action with a SurfaceController?

    Hi,

    I have the following site structure:

    • Home
      • Products
        • Product

    I am retrieving data and using custom routing and virtual nodes to create a route for single product that looks something like this:

    /products/product/23/crayola-crayons-24

    There is a button on that product page to Buy Now. When I click that button, I get the following error:

    {"The value of parameter 'id' must be either a string or an integer"} in my ProductViewModel at the line:

    public ProductViewModel()
                : this(new UmbracoHelper(UmbracoContext.Current).TypedContent((UmbracoContext.Current.PageId)))
            {
    
            }
    

    The Buy Now link looks like this:

    <a href="@Url.Action("AddToCart","ShoppingCart",new{Model})">BUY NOW</a>

    ShoppingCartController and AddToCart are as follows:

    public class ShoppingCartController : SurfaceController
    {
        public ActionResult AddToCart(ProductViewModel product)
        {
            var cart = new ShoppingCart {CreatedOn = DateTime.Now};
    
    
            var item = new ShoppingCartItem
            {
                Name = product.Name,
                Price = 699,
                Quantity = 1,
                ProductId = product.ProductId,
                Description = product.ShortDescription,
                Sku = product.PartNumber
            };
    
            cart.ShoppingCartItems.Add(item);
    
            using (var db = new ShoppingCartEntities())
            {
                db.SaveChanges();   
            }
    
    
            return CurrentUmbracoPage();
        }
    }
    

    When I click Buy Now, it never hits the controller, it immediately throws the error mentioned above. I tried using just a regular MVC controller, but then the BUY NOW link doesn't get rendered with the href, so you can't even click on it.

    The issue seems to be happening when I pass ProductViewModel which inherits from RenderModel into AddToCart, but if I just pass RenderModel, it hits AddToCart, but RenderModel is null.

    What I ended up doing was:

    @using (Html.BeginUmbracoForm("AddToCart", "ShoppingCart", new {   @Model} , FormMethod.Post))
        {
            @Html.HiddenFor(x=>x.Name)
            @Html.HiddenFor(x=>x.PartNumber)
            @Html.HiddenFor(x=>x.ProductId)
            @Html.HiddenFor(x=>x.ShortDescription)
    
            <input type="submit" value="BUY NOW"/>
        }
    

    However, without the hidden fields, when my form posts, the model posted to the action is null. Is there anyway to not use hidden fields?

Please Sign in or register to post replies

Write your reply to:

Draft