JQuery使用Json调用Controller/Action

标签 jquery asp.net-mvc

我有一个搜索页面,页面顶部是带有搜索按钮的搜索条件。屏幕底部是按下搜索按钮时的结果。在本例中,我有 6 个不同的搜索条件供用户输入。我想将所有条件捆绑到一个类中,以便我的 Controller 操作可以将 Json 对象作为一个类读取。使用 FireBug 我可以看到我的 Json 已正确构建。使用调试器我知道我的 Controller /操作正在被触发。但是,当我在 Controller /操作中使用调试器查看类对象时,所有属性均为 null 或零。

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetStudentByCritera(StudentSearchCriteraCV critera)
{
    // Get the Data 
    ViewData["MainData"] = studentBLLHdl.StudentFind(critera);
    return View();
}

JavaScript/JQuery

<script>
    $.ajax({
        url: "GetStudentByCritera",
        type: 'POST',
        data: dataToSend,
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        beforeSend: ClientSideValidate,
        success: function (result) {
            alert(result.Result);
            $('#SearchResult').html(result.Result).show();
            // UnBlock UI
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // UnBlock UI

            // not sure how to handel error
            alert("error happen when posting to 'GetStudentByCritera'")

            // typically only one of textStatus or errorThrown
            // will have info
            this; // the options for this ajax request
        }


    });

    function BuildJson() {
        // building Json

        var dataForClass = {
            "StudentSearchCriteraCV": [{
                "StudLname": $("input[name='StudentSearchCriteraCV.StudLname']").val(),
                "StudFname": $("input[name='StudentSearchCriteraCV.StudFname']").val(),
                "Ssn": $("input[name='StudentSearchCriteraCV.Ssn']").val(),
                "StudId": $("input[name='StudentSearchCriteraCV.StudId']").val(),
                "Sex": $("input[name='StudentSearchCriteraCV.Sex']").val(),
                "Race": $("input[name='StudentSearchCriteraCV.Race']").val()
            }]
        };

        return $.toJSON(dataForClass);
    }

    function ClientSideValidate() {
        // Block the UI
        alert("In the ClientSideValidate");

        // if error UNBlock UI
        // return true if client side data is good.

        return true;
    }
</script>

最佳答案

您的ajax调用只是一个异步HTTP post,因此数据参数只能是键值对,而不是JSON对象。如果您将 Class 的数据展平,它将起作用。

关于JQuery使用Json调用Controller/Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/745108/

相关文章:

.net - 我可以在 .net 4 上运行 asp.net mvc 1 吗?

javascript - 相当于 jQuery one() 的 JS

javascript - 导出为 .txt 并排显示所有 <p> 行,而不是逐行显示 javascript jquery

javascript - 使用Ajax读取远程文档的变量值

c# - 在 View 中使用接口(interface)类型作为模型并使用真实类型属性和验证的最佳实践

c# - Html.ActionLink<> 智能感知问题

jQuery TableSorter 插件初始化时出现错误 : cannot read property '0' of undefined

javascript - 使用 javascript 在图像上标记区域

asp.net-mvc - 保存 EF4 POCO 对象更改时更新关系

javascript - 剑道时间选择器中的格式错误