gpt4 book ai didi

jquery - ASP.NET MVC 在 Ajax 中获取异常消息

转载 作者:行者123 更新时间:2023-12-03 23:01:53 25 4
gpt4 key购买 nike

我有一个行动:

[HttpPost]
public ActionResult MyAction(MyModel model)
{
...
if (model.MyCondition == true)
throw new Exception("MyMessage);
....
}

我想在 Ajax 端获取消息“MyMessage”:

onSuccess: function () {
...
},
onError: function (jqXHR, textStatus, errorThrown) {
//I'd like get "MyMessage" here
}

知道如何做到这一点吗?当我检查调试器时,我看不到我的字符串。

最佳答案

实现错误属性是一个好方法。另外,我通常不会抛出异常,而是返回 status code根据错误。您可以通过 XMLHttpRequest.responseText 写入响应流并在 js 中访问:

if (model.MyCondition == true)
{
if (Request.IsAjaxRequest())
{
Response.StatusCode = 406; // Or any other proper status code.
Response.Write("Custom error message");
return null;
}
}

在js中:

...
error: function (xhr, ajaxOptions, errorThrown) {
alert(xhr.responseText);
}

关于jquery - ASP.NET MVC 在 Ajax 中获取异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com