2

我知道这个问题很熟悉,但我无法克服它。

这是我的控制器动作

public JsonResult AddToCart(int productId, int quantity = 1, int optionValue = 0)
{
  AjaxActionResponse res = new AjaxActionResponse();
  res.Result = ture;
  ......
  return Json(res, JsonRequestBehavior.AllowGet);
}

这是我的ajax请求

$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: "<%= Url.Action("AddToCart", "CartAjax") %>",
    data: ({'productId': productId, 'quantity': quantity, 'optionValue': optionValue}),
    dataType: "json",
    success: function (d) {
        if ($.isEmptyObject(d)) {
            return;
        }
        if (!d.Result) {
            alert(d.ErrorMessage[0].ErrorMessage);
        }
        else {
            $("#myCartBox").dialog("open");
        }
        return;
    }
});

当我运行 ajax 请求时弹出已知错误

此请求已被阻止,因为在 GET 请求中使用敏感信息可能会泄露给第三方网站。要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet。

我试图使 AddToCart 操作 [HttpPost] 可以接受,但此时:参数从未到达方法并且请求返回的缺少参数错误(500 int. serv 错误)

我只能使用 get 方法运行,但此时请求已被阻止:)

我错过了什么吗?或者 MVC2 Ajax 请求的正确方法是什么。WebForms 在从 JavaScript 调用方法方面非常成功,但我不能在 MVC 上做到这一点。

任何的想法?

4

2 回答 2

1

我不确定这是您的基本问题,但您不应该将内容类型设置为 text/html。这不是您要发送的或 MVC 所期望的。完全省略该参数,让 jQuery 将其设置为application/x-www-form-urlencoded,这是合适的。

于 2010-12-17T02:05:10.870 回答
1

您是否尝试过使用此方法签名使用 POST?

[HttpPost]
public ActionResult AddToCart(FormCollection form)

或使用数据绑定:

public class CartItem {
    public int productId {get; set;}
    public int quantity {get; set;}
    public int optionValue {get; set;}
}

然后:

 public ActionResult AddToCart(CartItem c)

不幸的是,我没有一个好的答案,但我已经通过这种方式解决了我自己的一些问题(而不是弄清楚如何使用路由很好地传递参数)。

于 2010-12-17T02:26:09.800 回答