我想将C#中的自定义错误设置为默认显示而不是xhr.responseText
。
如何将cSharpErrorMessage
传递给ajax错误?
这是我的C#代码:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static AjaxResult<string> GetAutoCompleteHtml(string termList)
{
const string cSharpErrorMessage = "Unable to generate autocomplete HTML.";
try
{
//some logic
}
catch (Exception ex)
{
//some logic
}
}
这是我的ajax功能:
function StartAutoCompleteSearch(termsList) {
if (termsList.length > 2) {
$.ajax({
url: '/Ajax/AjaxCalls.aspx/GetAutoCompleteHtml',
type: 'POST',
data: "{'termList':'" + termsList + "'}",
global: false,
datatype: JSON,
success: function(response) {
//some logic
},
error: function(xhr, response) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message + " Click OK to log back in ");
window.location = "/login";
}
});
}
}
答案 0 :(得分:1)
只是抛出异常。像这样:
throw new Exception(cSharpErrorMessage);
代码示例:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static AjaxResult<string> GetAutoCompleteHtml(string termList)
{
const string cSharpErrorMessage = "Unable to generate autocomplete HTML.";
try
{
//some logic
}
catch (Exception ex)
{
//some logic to clean up and then throw exception
throw new Exception(cSharpErrorMessage);
}
}
如果您需要将错误消息显示为ajax调用中的第三个参数,请尝试以下操作:
HttpContext.Current.Response.StatusCode = 500;
HttpContext.Current.Response.StatusDescription = cSharpErrorMessage;
HttpContext.Current.Response.End();
你的剧本:
error: function(xhr, response,errorThrown) {
alert(errorThrown + " Click OK to log back in ");
window.location = "/login";
}