【问题标题】:My Ajax call is passing a null stringified object to my JSonResult Action, Why?我的 Ajax 调用将一个空字符串化对象传递给我的 JSonResult 操作,为什么?
【发布时间】:2019-10-05 01:12:19
【问题描述】:

我的 Ajax 方法是在控制器中调用 action 方法,并且调用返回成功。但是,我传递的对象始终为空。

我已经阅读了很多,也许不是全部,因为有很多类似的问题。我尝试了不同的方法,例如从 ajax 函数中删除 dataType 和 contentType 的不同变体。我在操作中设置了断点并在脚本中设置了警报,以在发送到 JsonResult 操作之前验证对象不为空。我已验证来自 Action 方法的数据已到达 ajax 函数的成功部分。

以下是场景:我有一个 MVC Core 2.2 索引页面。我添加了一个搜索文本框。一切正常如果我在浏览器中阻止 JS,那么我知道 HTML 是正确的。但我想为“更愉快”的用户体验提供一个 Ajax 选项。实际上,我确实让 ajax 可以处理简单的硬编码字符串。但是现在由于某种原因传入的对象为空。

让我们从视图的脚本开始:

    //This is the Object I want passed through Ajax
    //class pageValues {
    //   constructor(){
    //       this.sortColumn = $("#inpSortColumn").val();
    //       this.sortOrder = $("#inpSortOrder").val();
    //       this.filter = $("#Filter").val();
    //       this.message = "";
    //       this.currentPage = $("#inpCurrentPage").val();
    //       this.recordsPerPage = $("#inpPageSize").val();
    //       this.recordCount = 0;
    //   }
    //}
    // I also tried as a simple variable without a constructor and added
    //    default values incase undefined values were causing issues
    var pageValues = {
        sortColumn:     ($("#inpSortColumn").val() == undefined ) ? "LastName" : $("#inpSortColumn").val(),
        sortOrder:      ($("#inpSortOrder").val() == undefined ) ? "ASC" : $("#inpSortOrder").val(),
        filter:         ($("#Filter").val() == undefined ) ? "" : $("#Filter").val(), 
        message:        ($("#inpMessage").val() == undefined ) ? "" : $("#inpMessage").val(), 
        currentPage:    ($("#inpCurrentPage").val() == undefined) ? 1: $("#inpCurrentPage").val(), 
        recordsPerPage: ($("#inpPageSize").val() == undefined) ? 5 : $("#inpPageSize").val(),
        totalRecords:   ($("#inpTotalRecords").val() == undefined ) ? 0 : $("#inpTotalRecords").val()
    };

    $(document).ready(function () {
        // If we are here, the browser allows JS
        // So, replace the submit buttons with Ajax functions
        ReplaceHtml();
    });

    function ReplaceHtml() {
        // Search Button
        var divSearch = $("#divSearchBtn");
        divSearch.hide();
        divSearch.empty();
        divSearch.append('<button id="btnAjaxSearch" type="button" ' +
            'class="" onclick="RequestRecords();">Search</button>');
        divSearch.show();
    }

    // Here we call the Ajax function passing the data object and the callback function
    function RequestRecords() {
        alert($("#Filter").val());    // This is just to Verify value is present
        AjaxCallForRecords(pageValues, ReturnedData);
    }

    // This is the callback function
    function ReturnedData(data) {
        // This verifies we hit the callback
        alert("inside ajax callback"); 
        // The Verification that the Object returned is valid.
        // The problem appeared here, 
        // The firstname was always the same no matter the Search Filter.
        // Telling me the object on the server side receiving the 'pageValues' 
        // had been recreated due to being null.
        alert(data.users[0].firstName);
    }

    // Of course, here is the ajax function
    // I have played around with data and content settings
    // When I changed those I got 'Response Errors' but could never get the ResponseText
    function AjaxCallForRecords(dataToSend, callback) {
        console.log(dataToSend); // This prove Data is here
        $.ajax({
            type: "GET",
            url: '@Url.Action("Index_Ajax","ApplicationUsers")',
            data: JSON.stringify(dataToSend),
            dataType: "json",
            contentType: "application/json",
            success: function (data) { callback(data); },
            error: function (data) { alert("Error. ResponseText: " + data.responseText); }
        });
    }
</script>

好的,现在到控制器:

    public JsonResult Index_Ajax([FromBody] UsersCodeAndClasses.PageValues pageValues)
    {
        // A break point here reveals 'pageValues' is always null - this is the problem.....
        // In the GetFilteredData function I do create a new 'pageValues' object if null
        // So my Search 'Filter' will always be empty, and I will always get all the records.

        // Get Records
        List<InputUser> users = _usersCode.GetFilteredData(pageValues);

        // The next block of code assembles the data to return to the view
        // Again the 'pageValues' is null because that is what gets passed in, or rather, never assigned

        //Build Return Data
        UsersCodeAndClasses.AjaxReturnData data = new UsersCodeAndClasses.AjaxReturnData()
        {
            pageValues = pageValues,
            users = users
        };

        return Json(data);
    }

最后,服务器端“pageValues”声明:

    public class PageValues
    {
        // Class used to pass page and sorting information to Ajax Call
        public string sortColumn { get; set; } = "LastName";
        public string sortOrder { get; set; } = "ASC";
        public string filter { get; set; } = "";
        public string message { get; set; } = "";
        public int currentPage { get; set; } = 1;
        public int recordsPerPage { get; set; } = 5;
        public int recordCount { get; set; }
    }
    public class AjaxReturnData
    {
        // Class is used to pass multiple data to the Ajax Call
        public PageValues pageValues { get; set; }
        public List<InputUser> users { get; set; }
    }

所以,我期待数据被传递,我只是不知道为什么服务器没有分配数据。我是新手,可以用有经验的眼光。

谢谢

【问题讨论】:

    标签: ajax model-view-controller


    【解决方案1】:

    只需在 Ajax 调用中将类型从 GET 更改为 POST。

    【讨论】:

      【解决方案2】:

      我花了更多时间研究有关 ajax 返回值和类的所有内容。 最终,我的班级格式不正确,一旦我改变它就开始工作了。我还将类型更改为 POST,我不想使用 POST 来读取记录。但我正在发送大量数据以跟上搜索、分页和排序的步伐。

      下面的代码虽然我觉得它很冗长,但有些部分可能是不必要的。希望它对某人有所帮助,请随时发表评论并帮助我解决可以帮助他人的事情。

      <script>
          // Class to use for ajax data
          class pageValues {
              constructor(){
                  this.sortColumn = ($("#inpSortColumn").val() == undefined) ? "LastName" : $("#inpSortColumn").val();
                  this.sortOrder  = ($("#inpSortOrder").val() == undefined) ? "ASC" : $("#inpSortOrder").val();
                  this.filter = ($("#Filter").val() == undefined) ? "" : $("#Filter").val();
                  this.message = ($("#inpMessage").val() == undefined) ? "" : $("#inpMessage").val();
                  this.currentPage = ($("#inpCurrentPage").val() == undefined) ? 1 : $("#inpCurrentPage").val();
                  this.recordsPerPage = ($("#inpPageSize").val() == undefined) ? 5 : $("#inpPageSize").val();
                  this.totalRecords= ($("#inpTotalRecords").val() == undefined) ? 0 : $("#inpTotalRecords").val();
              }
              get SortColumn()          { return this.sortColumn; }
              set SortColumn(value)     { this.sortColumn = value; }
              get SortOrder()           { return this.sortOrder; }
              set SortOrder(value)      { this.sortOrder = value;}
              get Filter()              { return this.filter; }
              set Filter(value)         { this.filter = value; }
              get Message()             { return this.message; }
              set Message(value)        { this.message = value; }
              get CurrentPage()         { return this.currentPage; }
              set CurrentPage(value)    { this.currentPage = value; }
              get RecordsPerPage()      { return this.recordsPerPage; }
              set RecordsPerPage(value) { this.recordsPerPage = value; }
              get TotalRecords()        { return this.totalRecords; }
              set TotalRecords(value)   { this.totalRecords = value; }
          }
      
          $(document).ready(function () {
              // If we are here, the browser allows JS
              // So, replace the submit buttons with Ajax functions
              ReplaceHtml();
          });
      
          function ReplaceHtml() {
              // Search Button
              var divSearch = $("#divSearchBtn");
              divSearch.hide();
              divSearch.empty();
              divSearch.append('<button id="btnAjaxSearch" type="button" ' +
                  'class="" onclick="RequestRecords();">Search</button>');
              divSearch.show();
          }
      
          // Here we call the Ajax function passing the data object and the callback function
          function RequestRecords() {
              alert($("#Filter").val());    // This is just to Verify value is present
              AjaxCallForRecords(new pageValues(), ReturnedData);
          }
      
          // This is the callback funtion
          function ReturnedData(data) {
              // The verification we hit the callback
              alert("inside ajax callback"); 
              alert(data.users[0].firstName);
          }
      
          // Ajax function
          function AjaxCallForRecords(dataToSend, callback) {
              console.log(dataToSend);
              $.ajax({
                  type: "POST",
                  url: '@Url.Action("Index_Ajax","ApplicationUsers")',
                  data: JSON.stringify(dataToSend),
                  dataType: "json",
                  contentType: "application/json",
                  success: function (data) { callback(data); },
                  error: function (data) { alert("Error. ResponseText: " + data.responseText); }
              });
          }
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多