我正在尝试使用敲除模板绑定来绑定问题列表。我成功获取数据和模板绑定。但是在下一个按钮点击事件我试图将viewmodel发送到控制器,但它在控制器中给出null值
我的jquery代码是这样的
$(document).ready(function () {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/Render/LoadSurveyQuestions?sg=" + getUrlVars()["g"] + "&stg=" + getUrlVars()["sig"],
success: function (result) {
var lstQns = JSON.parse(result);
viewmodel = ko.mapping.fromJS(lstQns);
ko.applyBindings(viewmodel, document.getElementById("tblQuestions"));
}
});
$("#btnNext").click(function () {
$.ajax({
async: true,
cache: false,
type: 'post',
url: "/Render/SaveSurveyQuestionOptions",
data: ko.toJSON(viewmodel),
success: function (result) {
}
});
});
});
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
控制器是这样的
[HttpPost]
public void SaveSurveyQuestionOptions(List<Question> listOfQuestions)
{
if (listOfQuestions.Count > 0)
{
Question objQuestion = new Question();
osurveymanager.InsertQuestionAnswers(objQuestion);
}
}
Here i am getting listOfQuestions as null value
请帮帮我 提前致谢
答案 0 :(得分:0)
问题是您从客户端发送JSON字符串
$("#btnNext").click(function () {
$.ajax({
async: true,
cache: false,
type: 'post',
url: "/Render/SaveSurveyQuestionOptions",
data: ko.toJSON(viewmodel), //toJSON converts your viewModel to JSON string
success: function (result) {
}
});
所以你应该在服务器端的字符串变量中接受它,所以你的控制器动作应该是:
[HttpPost]
public void SaveSurveyQuestionOptions(string listOfQuestions)
{
var Questions = JsonConvert.DeserializeObject(listOfQuestions);
//Now here Questions varibale contains the list Of question passed..
//from the client side
}
试试这个并告诉我它是否有帮助!