问题
I have the ajax is :
<script>
$( document ).ready(function(){
$('#addtocart').click(function () {
var size = $('#ddlsize').val();
var color = $('#ddlcolor').val();
var id ='@Model.ProductId';
alert(size + color +id);
$.ajax({
url: '@Url.Action("AddTocart", "ShoppingCart")',
data: {
id: id,
size: size,
color: color,
},
dataType: "html",
type: 'POST',
success: function (data) {
alert("Da them vao gio hang");
},
error: function () {
alert("Co loi xay ra vui long thu lai");
}
});
});
});
</script>
And in my controller
[HttpPost]
public ActionResult AddTocart(int id, string size, string color)
{
Product productitem = dbcon.Products.Where(p => p.ProductId == id).SingleOrDefault();
var cart = ShoppingCart.Getcart(this.HttpContext);
cart.AddtoCart(productitem, size, color);
return View();
}
without the httpget addtocart.When i click button addtocart,some time error in ajax,but it do the action addtocart and save in database,some time success and some time error but doesnt save database,i dont know what problem happend?
回答1:
Because of this syntax
url: '@Url.Action("AddTocart", "ShoppingCart")'
The url
option of the ajax call would be /ShoppingCart/AddTocart
, and since you call return View();
in your controller code
[HttpPost]
public ActionResult AddTocart(int id, string size, string color)
{
Product productitem = dbcon.Products.Where(p => p.ProductId == id).SingleOrDefault();
var cart = ShoppingCart.Getcart(this.HttpContext);
cart.AddtoCart(productitem, size, color);
return View();
}
You're telling the controller to open this url after inserting to database: /ShoppingCart/AddTocart
, which I would guess doesn't exist so you get the error because you don't have /Views/ShoppingCart/AddTocart.cshtml
or you don't have this method without [HttpPost]
attribute in ShoppingCartController
class.
public ActionResult AddTocart()
{
}
You should return json as follows
[HttpPost]
public ActionResult AddTocart(int id, string size, string color)
{
Product productitem = dbcon.Products.Where(p => p.ProductId == id).SingleOrDefault();
var cart = ShoppingCart.Getcart(this.HttpContext);
cart.AddtoCart(productitem, size, color);
return Json(new { success = true });
}
and change dataType
option to json
<script>
$( document ).ready(function(){
$('#addtocart').click(function () {
var size = $('#ddlsize').val();
var color = $('#ddlcolor').val();
var id ='@Model.ProductId';
alert(size + color +id);
$.ajax({
url: '@Url.Action("AddTocart", "ShoppingCart")',
data: {
id: id,
size: size,
color: color,
},
dataType: "json",
type: 'POST',
success: function (data) {
alert("Da them vao gio hang");
},
error: function () {
alert("Co loi xay ra vui long thu lai");
}
});
});
});
</script>
来源:https://stackoverflow.com/questions/26932369/error-with-the-ajax-and-transaction-in-mvc