如何通过AJAX状态代码从C#Webmethod获取数据?

时间:2018-10-15 10:47:11

标签: javascript c# ajax

我正在开发代码以检查服务器上是否已经存在数据。如果存在冲突,则程序必须返回状态码409。我可以通过ajax.success获取由webmethod返回的数据。但是,我无法通过ajax.statusCode获取数据。它总是返回错误:

  

TypeError:数据未定义

我尝试过this,但遇到错误

  

不可发音的成员“ Content”不能像方法一样使用

如何通过ajax.statusCode获取对象?

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:

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) {
    }
});
}

2 个答案:

答案 0 :(得分:0)

您可以这样做。使用Web API代替Web方法并返回HttpResponseMessage代替case

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);
 }
}

答案 1 :(得分:0)

如果您想使用网络方法,请更改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);
   }    
  }
  });
 }