jquery - 如何设置 jQuery ajax 帖子的 contentType 以便 ASP.NET MVC 可以读取它?

标签 jquery asp.net-mvc ajax

我有一些看起来像这样的 jQuery:

$.ajax({
     type: "POST",
     url: "/Customer/CancelSubscription/<%= Model.Customer.Id %>",
     contentType: "application/json",
     success: refreshTransactions,
     error: function(xhr, ajaxOptions, thrownError) {
         alert("Failed to cancel subscription! Message:" + xhr.statusText);
     }
});

如果被调用的操作导致异常,它最终会被 Global.asax Application_Error 捕获,其中我有一些如下代码:

var ex = Server.GetLastError();
if (Request.ContentType.Contains("application/json"))
{
     Response.StatusCode = 500;
     Response.StatusDescription = ex.Message;
     Response.TrySkipIisCustomErrors = true;
}
else
{
     // some other way of handling errors ...
}

当我执行发布请求的脚本时,Request.ContentType 始终是空字符串,因此不会命中第一个 if block 。我是否应该在 ajax“contentType”中放入其他值?或者我还有另一种方法来告诉 asp.net 内容类型应该是“application/json”?

澄清

我试图实现的目标是将异常消息传递回ajax错误事件。目前,即使 IF block 被绕过,错误事件也会正确引发警报框,但消息为“未找到”。

如您所见,我正在尝试将异常消息设置为 Response.StatusDescription,我相信 ajax 错误中的 xhr.statusText 已设置为该值。

最佳答案

根据这篇文章:http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ “当没有包含数据时,jQuery 无法正确设置指定的内容类型。”

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebService.asmx/WebMethodName",
  data: "{}",
  dataType: "json"
});

关于jquery - 如何设置 jQuery ajax 帖子的 contentType 以便 ASP.NET MVC 可以读取它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202857/

相关文章:

c# - 查找 asp.net MVC 中 View 的所有引用

javascript - Laravel 将错误消息添加到 ajax post

jquery - 设置水平滚动条固定位置在显示屏底部

jquery - 动态改变 CSS 样式高度

javascript - 使用 jquery 切换时如何更改事件切换 anchor 的样式?

jquery - 如何定期触发 AJAX 请求?

asp.net - 更新面板不更新内容

javascript - 如何选中和取消选中HighCharts Linechart中的所有图例元素?

asp.net-mvc - 无法在 ASP.NET MVC 项目中添加 Controller

C#:枚举中的按位运算符(MVC 中的自定义授权)