根据WebMethod中提供的条件从WebMethod返回值

时间:2013-05-13 15:06:35

标签: c# asp.net jquery

我有一个jQuery Ajax WebMethod调用,如下所示:

<script type="text/javascript">
    $(document).ready(function () {
        $("#btnsubmit").click(function () {

            var arr = new Array();
            arr.push($("#control1").val()); arr.push($("#control2").val()); arr.push($("#control13 option:selected").val()); arr.push($("#control4 option:selected").val()); arr.push($("#control15 option:selected").val());

            var requestedData = JSON.stringify(arr);
            requestedData = "{'details':'" + requestedData + "'}";

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "EmployeeDemotion.aspx/Save",
                data: requestedData,
                dataType: "json",
                success: function (result) {
                  //check the value returned from the WebMethod and provide alerts accordingly

                },

                error: function (result) {
                    alert("Error");
                }

            });
        });

    });
</script>

,WebMethod如下:

 [WebMethod(EnableSession = true)]
     public static InsertDetails[] Save(string details)
        {

            DataTable dt = new DataTable(); DataTable dts = new DataTable();

            List<InsertDetails> data = new List<InsertDetails>();
            JavaScriptSerializer js = new JavaScriptSerializer();
            string[] Tags = js.Deserialize<string[]>(details);
            object[] obj = new object[8];
            obj[0] = Tags[0].ToString(); obj[1] = Tags[1].ToString(); obj[2] = Tags[2].ToString(); obj[3] = Tags[3].ToString();
            obj[4] = Tags[4].ToString(); 


            int a = //say condition 1
            int b = //say condition 2
            if (a< b)
            {

             //insert into database and set a value which says the insertion has succeeded

            }
            else
            {
                //alert that data cannot be inserted
            }

            return data.ToArray();
        }

现在我需要将任何可能类型的值(布尔值,数组,字符串,整数或其他)返回到ajax方法,以便ajax方法中的success函数提醒插入状态(如te片段中所述) );即;应该返回一个值以及最后一个语句“return data.ToArray();”到ajax方法。 我不需要返回元素'data',验证插入的值应该与'data'或任何其他形式一起返回。

1 个答案:

答案 0 :(得分:4)

不确定你想要什么。是否希望将数据和标志都返回到客户端函数或仅返回标志。

  • 案例1:您想要的只是返回有关save

    内发生的操作的消息

    只需像这样更改您的保存方法

    [WebMethod(EnableSession = true)]
    public static string Save(string details)
    {
          string message =string.Empty;
    
          /// rest of the usual code of yours   
          ///
          if (a< b)
          {
             //rest of the code
             message = "Insertion Successful";
          }
          else
          {
             //rest of the code
             message = "Error Occured";
          }
    }
    

    在ajax success内的客户端,简单地执行此操作:

    success: function (result) {
                   alert(result.d);
    }
    
  • 案例2:您希望在插入成功的情况下发送数据

    创建一个包装器并将数据和标志都附加到它上面。序列化它 然后将其发送到客户端功能。即

    //wrapper class
    public class ServiceResponse
    {
       public bool IsSuccess {get;set;}
       public string Message {get;set;}
    }
    

    现在在save内执行此操作:

    [WebMethod(EnableSession = true)]
    public static string Save(string details)
    {
          ServiceResponse serviceResponse =new ServiceResponse();
    
          /// rest of the usual code of yours   
          ///
          if (a< b)
          {
             //rest of the code
              serviceResponse.IsSuccess= true;
              serviceResponse.Message = String.Join(",",data.ToArray());
          }
          else
          {
             //rest of the code
             serviceResponse.IsSuccess = false;
          }
    
        return new JavaScriptSerializer().Serialize(serviceResponse);
    }
    

    并在您的客户端方法中使用它,如:

      success: function (result) {
              var jsonData = $.parseJSON(result.d);
              if(jsonData.IsSuccess){
                  alert('success');
                  grid.data(jsonData.Message);
              }
              else{
                  alert('failure');
              } 
      }