对[WebMethod]的Ajax调用抛出异常

时间:2014-12-10 12:46:31

标签: c# asp.net ajax asp.net-ajax

我正在尝试将SQL Server数据作为JSON发回。在Button1按下,id以JSON格式从Ajax Post传递给[WebMethod]

jsonobject调用jsondb.mdf,其中包含表格jsondata以及列idd, datetime, col1, col2col3,其中包含数据。

Default.aspx.cs

    [System.Web.Services.WebMethod]
    public static string GetJSONdata(string id1)
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
        string cmdStr = "SELECT ([idd],[datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=@idd;";
        try
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@idd", id1);
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                        dt = ds.Tables[0];
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }

        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row;

        foreach (DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();

            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }

            rows.Add(row);
        }

        var json2 = serializer.Serialize(rows);
        return json2;
    }

Default.aspx的

<script type="text/javascript" src="~/Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%= Button1.ClientID %>").click(function () {
            var id = $("#<%= TextBox1.ClientID %>").val();
            var data = { ID:id };
            var json1 = JSON.stringify(data);
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetJSONdata",
                data: json1,
                dataType: "json",
                success: function (result) {
                    $("#<%= TextBox2.ClientID %>").val(result.ID);
                    $("#<%= TextBox3.ClientID %>").val(result.datetime);
                    $("#<%= TextBox4.ClientID %>").val(result.col1);
                    $("#<%= TextBox5.ClientID %>").val(result.col2);
                    $("#<%= TextBox6.ClientID %>").val(result.col3);
                },
                error: function (Msg) {
                    $("#<%= Label1.ClientID %>").text('failed:' + Msg.status +  '    response:' + Msg.responseText);

                }
            }); return false;
        });
    });

错误代码:

  

失败:500响应:{&#34;消息&#34;:&#34;无效的Web服务调用,缺少参数值:\ u0027id1 \ u0027。&#34;,&#34; StackTrace&#34; :&#34; at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target,IDictionary 2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary 2参数)\ r \ n在System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context,WebServiceMethodData methodData,IDictionary`) 2 rawRarams)\ r \ n在System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)&#34;,&#34; ExceptionType&#34;:&#34; System.InvalidOperationException&#34; }

1 个答案:

答案 0 :(得分:1)

 type: "POST",
                    async: false,
                    url: "Default.aspx/GetJSONdata",
                    data: "{id1:id}",// Change Name As Per You WEBMETHOD 
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",

//执行此更改可能会帮助您

1)创建班级

public class ABC
        {
            public string idd{ get; set; }
            public string datetime{ get; set; }
            public string col1{ get; set; }
            public string col2{ get; set; }
            public string col3{ get; set; }

        }

2)创建Webmethod

  [webmethod]
  public static ABC[] GetJSONdata(string id1)
        {
            MasterLogic ml = new MasterLogic();
             DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
    string cmdStr = "SELECT ([idd],[datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=@idd;";
    try
    {
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@idd", id1);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(ds);
                    dt = ds.Tables[0];
                }
            }
        }
    }
    catch (Exception ex)
    {
    }
            List<ABC> ProjectStatus = new List<ABC>();
            foreach (DataRow dr in dt.Rows)
            {
                ABC ps = new ABC();
              ps.id=Convert.ToInt32(dr["Columnname"]);
             // Do same To set value OF Properties
                ProjectStatus.Add(ps);

            }
            return ProjectStatus.ToArray();
        }

//在ASPX页面上获取Json

success: function (response) {
     for (var i = 0; i < response.d.length; i++) {
     //Write Your logic
    }
}