jquery post onsuccess返回null对象

时间:2017-06-29 15:06:29

标签: javascript c# jquery asp.net

我在返回数据表时在json post success函数中获取null对象。我已经搜索过这个问题,但无法找到它,需要您的帮助。以下是我的代码。

脚本和风格:

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <style type="text/css">
    /* Panel Dropdown  */
     .clickable
    {
        cursor: pointer;
    }

    .panel-heading span
    {
        margin-top: -20px;
        font-size: 15px;
    }
</style>
<script type="text/javascript">
    $(document).on('click', '.panel-info span.clickable', function (e) {
        var $this = $(this);
        if (!$this.hasClass('panel-collapsed')) {
            $this.parents('.panel').find('.panel-body').slideUp();
            $this.addClass('panel-collapsed');
            $this.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
        } else {
            $this.parents('.panel').find('.panel-body').slideDown();
            $this.removeClass('panel-collapsed');
            $this.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
        }
    })
    $(function () {

        var max_fields = 10;
        var x = 0;
        var y;
        $('#add').click(function () {
            if (x < max_fields) {
                x++;
                if (x == 1) {
                    y = x;
                } else {
                    y = y + 3;
                }
                $("#addblock").before('<div class="col-md-14"><div class="panel panel-info">' +
                 '<a href="#" class="remove_field" title="Remove">Remove</a>' +
                 '<div class="panel-heading">' +
                 '<span class="menu-icon append-icon"></span><strong>Workout Type and Rates ' + x + '</strong>' +
                 '<span class="pull-right clickable"><i class="glyphicon glyphicon-chevron-up"></i></span>' +
                 '</div>' +
                 ' <div class="panel-body">' +
                 ' <table id="tblPanel' + x + '"><tr><td>Workout Type</td><td><input type="textbox" id=txtWorkoutType' + x + '></td></tr>' +
                 '<tr><td>Description</td><td><input type="textbox" id=txtDesc' + x + '></td></tr>' +
                 '<tr><td>Month</td><td><input type="textbox" id=txtMonth' + y + '></td><td><input type="textbox" id=txtMonth' + (y + 1) + '></td><td><input type="textbox" id=txtMonth' + (y + 2) + '></td><td><input type="textbox" id=txtMonth' + (y + 3) + '></td><td><input type="textbox" id=txtMonth' + (y + 4) + '></td></tr>' +
                 '<tr><td>Rate</td><td><input type="textbox" id=txtRate' + y + '></td><td><input type="textbox" id=txtRate' + (y + 1) + '></td><td><input type="textbox" id=txtRate' + (y + 2) + '></td><td><input type="textbox" id=txtRate' + (y + 3) + '></td><td><input type="textbox" id=txtRate' + (y + 4) + '></td></tr>' +
                 '<tr><td>Discount</td><td><input type="textbox" id=txtDiscount' + y + '></td><td><input type="textbox" id=txtDiscount' + (y + 1) + '></td><td><input type="textbox" id=txtDiscount' + (y + 2) + '></td><td><input type="textbox" id=txtDiscount' + (y + 3) + '></td><td><input type="textbox" id=txtDiscount' + (y + 4) + '></td></tr>' +
                 '</table>' +
                 '</div></div></div>');

                $("#hdnPanelinputCount").val(x);

            } else {
                alert("Only 10 entries are allowed");
            }

        });
        $(document).on('click', '.remove_field', function (e) {
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        });
    });

</script>

体:

<div class="container">
        <div class="row">
          <div class="panel panel-success" id="addblock">
                <div class="form-group col-md-3 col-sm-3">
                    <input type='button' class="btn btn-primary" value="Add Workout Types" id="add" />
                </div>
            </div>


        </div>
        <input type='button' class="btn btn-primary" value="Submit" id="btnSubmit" />
    </div>
    <div>
        <table id="tbl">
            <tr>
                <th>Workout Type</th>
                <th>Month</th>
                <th>Rate</th>
                <th>Discount</th>
            </tr>
        </table>
    </div>
    <input id="hdnPanelinputCount" hidden="hidden" />

脚本:

     $("#btnSubmit").on('click', function () {
         var rowcount = $("#hdnPanelinputCount").val();
         var m = 0;
         var n;
         if (m < rowcount) {
             $("table[id^='tblPanel']").each(function () {
                 m++;
                 if (m == 1) {
                     n = m;
                 } else {
                     n = n + 3;
                 }
                 var WorkoutType = $("#txtWorkoutType" + m).val();
                 var Month1 = $("#txtMonth" + n).val();
                 var Month2 = $("#txtMonth" + (n + 1)).val();
                 var Month3 = $("#txtMonth" + (n + 2)).val();
                 var Rate1 = $("#txtRate" + n).val();
                 var Rate2 = $("#txtRate" + (n + 1)).val();
                 var Rate3 = $("#txtRate" + (n + 2)).val();
                 var Discount1 = $("#txtDiscount" + n).val();
                 var Discount2 = $("#txtDiscount" + (n + 1)).val();
                 var Discount3 = $("#txtDiscount" + (n + 2)).val();
                 /* Validations */
                 if (WorkoutType === "") {
                     alert("Please enter Workout type");
                     $("#txtWorkoutType" + rowcount).focus();
                     return false;
                 }
                 if (Month1 === "") {
                     alert("First Month cannot be blank");
                     $("#txtMonth" + rowcount).focus();
                     return false;
                 }
                 if (Month1 != "" || Month2 != "" || Month3 != "") {
                     if (Rate1 === "") {
                         alert("First Month Rate cannot be blank");
                         $("#txtRate" + rowcount).focus();
                         return false;
                     }
                     if (Rate2 === "") {
                         alert("Please put rate corresponding of month");
                         $("#txtRate" + rowcount).focus();
                         return false;
                     }
                     if (Rate3 === "") {
                         alert("Please put rate corresponding of month");
                         $("#txtRate" + rowcount).focus();
                         return false;
                     }
                     //if (Rate1 != "" || Rate2 != "" || Rate3 != "")
                     //{
                     //    if (Discount1 === "" || Discount2 === "" || Discount3 === "") {
                     //        alert("Please put discount corresponding of rate");
                     //        return false;
                     //    }
                     //}
                 }

                 var strtable = '<tr><td>' + WorkoutType + '</td><td>' + Month1 + '</td><td>' + Rate1 + '</td><td>' + Discount1 + '</td></tr>' +
                   '<tr><td>' + WorkoutType + '</td><td>' + Month2 + '</td><td>' + Rate2 + '</td><td>' + Discount2 + '</td></tr>' +
                   '<tr><td>' + WorkoutType + '</td><td>' + Month3 + '</td><td>' + Rate3 + '</td><td>' + Discount3 + '</td></tr>';

                 $("#tbl").append(strtable);

             });

         }
         var HTMLtbl =
                       {
                           getData: function (table) {
                               var data = [];
                               table.find('tr').not(':first').each(function (rowIndex, r) {
                                   var cols = [];
                                   $(this).find('td').each(function (colIndex, c) {

                                       if ($(this).children(':text').length > 0)
                                           cols.push($(this).children('input').val().trim());
                                       else
                                           cols.push($(this).text().trim());
                                   });
                                   data.push(cols);
                               });
                               return data;
                           }
                       }

         var data = HTMLtbl.getData($('#tbl'));
         var parameters = {};
         parameters.array = data;
         alert(parameters);
         var request = $.ajax({
             async: true,
             cache: false,
             dataType: "json",
             type: "POST",
             contentType: "application/json; charset=utf-8",
             url: "FitnessStudioAdmin.aspx/SaveData",
             data: JSON.stringify(parameters),
             success: function (data, status, jqXHR) {
                 var objdata = $.parseJSON(data.d);
                 alert(objdata);
             },
             error: function (jqXHR, status, err) {
                 alert("Local error callback." + err);
         }  
         });
     });
 </script>

CS页面

  [WebMethod]
public static string SaveData(string[][] array)
{
    DataTable dt = new DataTable();
     dt = new DataTable();
        dt.Columns.Add("WorkoutType");
        dt.Columns.Add("Description");
        dt.Columns.Add("Month");
        dt.Columns.Add("Rate");
        dt.Columns.Add("Discount");
        dt.Columns.Add("Results");
        foreach (var arr in array)
        {
            DataRow dr = dt.NewRow();
            dr["WorkoutType"] = arr[0];
            dr["Description"] = arr[0];
            dr["Month"] = arr[1];
            dr["Rate"] = arr[2];
            dr["Discount"] = arr[3];
            dr["Results"] = "";
            dt.Rows.Add(dr);
        }

        String result = null;
        DataSet ds = new DataSet();
        ds.Tables.Add(dt);
        result = DataSetToJSON(ds);
        return result;
}
public static string DataSetToJSON(DataSet ds)
{

    Dictionary<string, object> dict = new Dictionary<string, object>();
    foreach (DataTable dt in ds.Tables)
    {
        object[] arr = new object[dt.Rows.Count + 1];
        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            arr[i] = dt.Rows[i].ItemArray;
        }
        dict.Add(dt.TableName, arr);
    }

    JavaScriptSerializer json = new JavaScriptSerializer();
    return json.Serialize(dict);
}

我还需要你们的建议,上面的代码是在动态面板中生成动态面板和输入控件,现在我需要复选框列表,它将来自数据库并填充每个面板中的数据。我怎么能完成它?

1 个答案:

答案 0 :(得分:0)

你真的不应该使用JavaScript序列化程序,微软建议使用Newtonsoft Json.Net代替。

  

Json.NET应该用于序列化和反序列化。提供   启用AJAX的序列化和反序列化功能   应用

他们的方法是:

return JsonConvert.SerializeObject<Example>(example);

您的方法签名也应该是:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Example> GetExampleDataAsJson()
{
     // Return normal object, this will return as Json for you in the decorator.
}

另一个选项是HttpHandler文件。

public void ProcessRequest(HttpContext context)
{
     var content = JsonConvert.SerializeObject<Example>(example);
     context.Response.Write(content);
     context.Response.End();
} 

你有各种各样的方法,同时请记住,如果你返回json,你不需要Json.Parse(...),因为它已经作为有效的Json对象返回。

此外,您的代码中的主要问题。您应该通过HttpContext流序列化并推送请求。如果你使用它,类似于处理程序,它应该将有效值传递给Ajax。此外,您可以利用Fiddler来验证来往的请求。

相关问题