1

I've been at this for a while but due to the fact that I'm a new at MVC, I still need to figure it out. Basically what I need to do is to add an item to a cart and to do so I need to pass the ID of the item and the quantity to the controller.

I tried doing this by using AJAX. Alas it failed.

My Javascript:

    <script type="text/javascript">
function cart(id) {
    alert(id + " " + $('input:text[name=quantity]').val());  
    var param = {
        userId: id,
        quantity: $('input:text[name=quantity]').val()
    };

    $.ajax({
        url: '/Cart/AddToCart',
        contentType: "application/x-www-form-urlencoded",
        type: "POST",
        datatype: "json",
        data: param,
        error: function (xmlHttpRequest, errorText, thrownError) {
            alert(xmlHttpRequest + "|" + errorText + "|" + thrownError);
        },
        success: function (data) {
            if (data != null) {
                alert("success");
            }
        }
    });
}

Now this is the HTML that links to it :

<input type="text" name="quantity"/>  


<button type="button" onclick="cart(@Model.ProductID)">Add to Cart!</button>

The Controller is placed in the Folder Controllers and is named "CartController". The method that I want to access is AddToCart, attached below:

[HttpPost]
    public ActionResult AddToCart(int userid, string quantity)
    {
        if (User.Identity.IsAuthenticated)
        {
            try
            {
                new ProductService.ProductsServiceClient().AddProducttoCart(User.Identity.Name.ToString(), id, Convert.ToInt16(quantity));
                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                ViewBag.Message("Could not add to Cart ");
                return RedirectToAction("Index", "Home");
            }

        }
        else
        {
            ViewBag.Message("Not logged in");
            return RedirectToAction("Index", "Home");

        }
    }

The program reads the parameters alright, but then displays: [object Object]|error|Internal Server Error

Thanks a lot for any help whatsoever. I have been on this for hours on end now :(

5
  • Is your controller returning the value you want? Commented Apr 8, 2014 at 20:36
  • Is this a asp.net mvc or webapi controller? Commented Apr 8, 2014 at 20:36
  • why you have contentType: "application/x-www-form-urlencoded" ? Commented Apr 8, 2014 at 20:39
  • I removed contentType (not sure why I had added it myself) and it work! Thank you so much for the help! I feel silly now haha Commented Apr 8, 2014 at 20:45
  • You can accept my answer. I let you something to read . Commented Apr 8, 2014 at 20:46

2 Answers 2

1

I think ur problem is at the model binder as ur contentType is application/x-www-form-urlencoded, you'll never receive ur params.

Check this : differences in application/json and application/x-www-form-urlencoded .

Sign up to request clarification or add additional context in comments.

Comments

1

For rest calls (like you do with your ajax call above) I recommend you to use webapi controller. serialize your id as integer not as string by using javascript method parseInt(). Of course your request should have the mime type application/json instead of application/x-www-form-urlencoded.

Then on serverside you do something like this:

public YourController() {
    /* create dependencies with dic or by hand */
    _productService = new ProductService();
}

[HttpPost]
public HttpResponseMessage AddToCart(int id, string quantity)
{
    if (User.Identity.IsAuthenticated)
    {
        try
        {
            _productService.ProductsServiceClient().AddProducttoCart(User.Identity.Name.ToString(), id, Convert.ToInt16(quantity));
            return Request.CreateResponse(HttpStatusCode.Ok);
        }
        catch(EntityNotExistsException ex)
        {
            /* check for null pointer for instance id */
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        catch (Exception ex)
        {
            ViewBag.Message("Could not add to Cart ");
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.Forbidden);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.