【问题标题】:MVC 3 Controller not recognizing JSON passed back by jQuery AJAXMVC 3 控制器无法识别由 jQuery AJAX 传回的 JSON
【发布时间】:2011-07-23 22:03:51
【问题描述】:

我有一个 MVC 3 应用程序,它使用 jQuery AJAX 触发控制器操作以返回部分视图。

客户端代码:

function getCustomerList(searchCriteria) {
    $.ajax({
        url: 'Home/GetCustomerList',
        type: 'POST',
        data: '{searchString:"' + searchCriteria + '"}',
        success: function (result) {
            $("#customerTabBody").html(result);
        }
    });
};

控制器代码:

[HttpPost]
public ActionResult GetCustomerList(string searchString)
{
    var custService = new CustomerViewModels();
    var custListVM = custService.GetSearchList(searchString);

    return PartialView("GetCustomerList", custListVM);
}

当我触发客户端 jQuery 时,我可以通过 Firebug 看到 searchString 正在发送并且格式正确。以下是 Firebug 显示的帖子消息:

{searchString:'ar'}

并且 Firebug 能够正确解析 JSON。如果我在控制器代码中设置断点并测试 searchString 参数的值为 NULL。但是,如果我只是对 JSON 进行硬编码:

function getCustomerList(searchCriteria) {
    $.ajax({
        url: 'Home/GetCustomerList',
        type: 'POST',
        data: {searchString:'ar'},
        success: function (result) {
            $("#customerTabBody").html(result);
        }
    });
};

它工作得很好,并且控制器参数被正确填充。

我做错了什么,以至于当我参数化我的 JSON 字符串时它失败了?

谢谢

【问题讨论】:

    标签: jquery asp.net-mvc json


    【解决方案1】:

    试试这样:

    function getCustomerList(searchCriteria) {
        $.ajax({
            url: 'Home/GetCustomerList',
            type: 'POST',
            data: { searchString: searchCriteria },
            success: function (result) {
                $('#customerTabBody').html(result);
            }
        });
    }
    

    这将确保发送到控制器的数据经过正确的 URL 编码。此外,您还没有显示如何/在何处调用此 getCustomerList 函数,但如果它是在单击某个锚点或按钮时,请确保您也取消了默认操作。

    【讨论】:

    • 伙计们——我们赢了!谢谢达林
    • 奇怪的是 StackOverflow 让您等待大约 12 分钟才能将答案标记为正确。
    猜你喜欢
    • 2019-06-27
    • 2012-10-20
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2013-04-22
    • 2016-03-17
    相关资源
    最近更新 更多