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