视图传递到控制器

视图传递到控制器

本文介绍了JQUERY ajax 将值从 MVC 视图传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是将 txtComments 的值从 View(使用 jquery/ajax)传递给 Controller.

What I want is to pass the value of txtComments from View (using jquery/ajax) to Controller.

问题是 ajax/jquery 不接受脚本标签作为字符串.意思是,当我在 txtComments 中输入任何脚本/html 标记时,ajax 会转到错误函数,而无法进入控制器.

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:

        $('#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').serialize() 而不是 escape(comments) 但还是一样.

I also tried $('#txtComments').serialize() instead of escape(comments) but still the same.

推荐答案

尝试使用 $.ajax 函数的 data 选项.更多信息这里.

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 视图传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 13:55