JQUERY AJAX传递值从MVC视图到控制器 [英] JQUERY ajax passing value from MVC View to Controller
问题描述
我要的是通过txtComments从查看值(使用jQuery / AJAX)来控制。
What I want is to pass the value of txtComments from View (using jquery/ajax) to Controller.
问题是AJAX / jQuery的不接受脚本标记为字符串。意思是,当我输入了ajax转到误差函数,不能够进去的控制器,txtComments任何脚本/ html标记
The problem is the ajax/jquery doesn't accept script tags as string. Meaning, when I input any script/html tag in the txtComments the ajax goes to the error function and not being able to go in the controller.
下面是jQuery的:
Here is the 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.");
}
});
});
下面是控制器:
[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')。序列化()
,而不是逃逸(评论),但仍是相同的。
I also tried $('#txtComments').serialize()
instead of escape(comments) but still the same.
推荐答案
尝试使用数据
的 $。阿贾克斯$ c选项$ C>功能。这里更多信息。
Try using the data
option of the $.ajax
function. More info 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视图到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!