我有一个搜索页面,页面顶部是带有搜索按钮的搜索条件。屏幕底部是按下搜索按钮时的结果。在本例中,我有 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/