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 :(

tereško
  • 58,060
  • 25
  • 98
  • 150
NetUser101
  • 272
  • 2
  • 5
  • 20

2 Answers2

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 .

Community
  • 1
  • 1
Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54
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);
    }
}
Nando
  • 813
  • 2
  • 8
  • 18