[英]How to get data from C# Webmethod via AJAX statuscode?
I am developing a code to check whether a data already exist on the server or not. 我正在开发代码以检查服务器上是否已经存在数据。 If there is a conflict, then the program must return status code 409. I can get the data returned by the webmethod via ajax.success. 如果存在冲突,则程序必须返回状态码409。我可以通过ajax.success获取由webmethod返回的数据。 However, I cannot get the data via ajax.statusCode. 但是,我无法通过ajax.statusCode获取数据。 It always returns error: 它总是返回错误:
TypeError: data is undefined TypeError:数据未定义
I have tried this but I got an error 我已经尝试过了,但是出现错误
Non-invocable member "Content" cannot be used like a method 不可说成员“内容”不能像方法一样使用
How do I get my object via ajax.statusCode? 如何通过ajax.statusCode获取对象?
C#: C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Case CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
HttpContext.Current.Response.StatusCode = 409;
return caseResponse;
}
else
{
HttpContext.Current.Response.StatusCode = 200;
return caseResponse;
}
}
catch (Exception ex)
{
HttpContext.Current.Response.StatusCode = 500;
return null;
}
}
JS: JS:
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
statusCode: {
409: function (data, response) {
//how do I get the "data" from WebMethod here?
loadCase(ID, data);
//TypeError: data is undefined
}
},
success: function (data, status) {
loadCase(ID, data);
},
error: function (data) {
}
});
}
You can do like this. 你可以这样 Use Web API instead of Web method and return HttpResponseMessage instead of case 使用Web API代替Web方法并返回HttpResponseMessage代替大小写
public HttpResponseMessage CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
return Request.CreateResponse( HttpStatusCode.Conflict, caseResponse );
}
else
{
return Request.CreateResponse( HttpStatusCode.OK, caseResponse );
}
}
catch (Exception ex)
{
return Request.CreateResponse( HttpStatusCode.InternalServerError, null);
}
}
If you want to use the web method approach then change the ajax and try to parse the error in errro function as given below 如果要使用Web方法,请更改ajax并尝试解析errro函数中的错误,如下所示
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data, status) {
loadCase(ID, data);
},
error: function (jqXHR, textStatus, thrownError) {
if(jqXHR.status =="409" ){
var data= jqXHR.responseJSON;
loadCase(ID, data);
}
else
{
console.log(textStatus);
}
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.