如何使用asp.net mvc3中的jquery函数将值从视图传递到控制器

Bha*_*gav 1 javascript jquery asp.net-mvc-3

我必须将值从视图传递给控制器​​,控制器具有将调用webmethod以将值设置为数据库的操作方法.我怎样才能做到这一点?

  • 不需要创建使用模型的视图.

我有一个视图,从数据库中获取值,并有一个注释链接.点击评论一个textarea框将打开并提供一些输入后.将点击"确定"按钮.

点击按钮确定我正在打电话

    $('a.comment').livequery("click", function (e) {
    var getpID = $(this).parent().attr('id').replace('commentBox-', '');
    var comment_text = $("#commentMark-" + getpID).val();
    //alert(getpID);
    //alert(comment_text);
    if (comment_text != "Write a comment...") {
        //$.post("/Home/SetComment?comment_text=" + comment_text + "&post_id-= " + getpID, {

    }, function (response) {

        $('#CommentPosted' + getpID).append($(response).fadeIn('slow'));
        //            $("#commentMark-" + getpID).val("Write a comment...");
        $("#commentMark-" + getpID).val();
    });
}
Run Code Online (Sandbox Code Playgroud)

现在我该怎么做才能将getpId和comment_text值赋予控制器SetComment动作?

Dar*_*rov 5

您可以使用$.post方法将它们作为AJAX请求发送:

var url = '@Url.Action("SetComment", "Home")';
var data = { commentText: comment_text, postId: getpID };
$.post(url, data, function(result) {
    // TODO: do something with the response from the controller action
});
Run Code Online (Sandbox Code Playgroud)

将发布到以下操作:

public ActionResult SetComment(string commentText, string postId) 
{
    ...
}
Run Code Online (Sandbox Code Playgroud)