JQUERY ajax 将值从 MVC View 传递到 Controller

标签 jquery ajax asp.net-mvc model-view-controller

我想要的是将 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/

相关文章:

c# - 为什么我的 MVC 应用程序中的日期格式错误?

c# - Entity Framework 尝试添加数据库中已有表的迁移

Javascript 和 JQuery : what's the difference between $x and x as variable declarations?

javascript - Comet(服务器推送)是我正在寻找的答案吗?

php - cometd 是如何工作的?如何编写个人对个人的 cometd 聊天应用程序

php - JQuery Ajax 在创建响应时引入响应

jquery - asp.net mvc文件上传ajax帖子

javascript - 如何在ajax函数调用中发送var来发送POST?

javascript - 来自服务器的 AngularJS 绑定(bind)响应未在 View 中更新

jquery - 在 jQuery 中使用 'this' 关键字的上下文