我想要的是将 txtComments 的值从 View (使用 jquery/ajax)传递到 Controller 。
问题是 ajax/jquery 不接受脚本标签作为字符串。意思是,当我在 txtComments 中输入任何 script/html 标记时,ajax 会转到错误函数,并且无法进入 Controller 。
这是 jQuery:
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>?id=' + selectedId + '&comments=' + escape(comments),
type: "post",
cache: false,
success: function (savingStatus) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
这是 Controller :
[HttpPost]
public ActionResult SaveComments(int id, string comments){
var actions = new Actions(User.Identity.Name);
var status = actions.SaveComments(id, comments);
return Content(status);
}
我还尝试了 $('#txtComments').serialize()
而不是 escape(comments),但仍然相同。
最佳答案
尝试使用$.ajax
函数的data
选项。更多信息here .
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatus) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
关于JQUERY ajax 将值从 MVC View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8486132/