jQuery 从 $.Ajax Post 返回 PartialView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3490059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:32:25  来源:igfitidea点击:

Return a PartialView from $.Ajax Post

asp.net-mvcjquery

提问by griegs

I have the following code;

我有以下代码;

        $.ajax({
            url: "/Home/jQueryAddComment",
            type: "POST",
            dataType: "json",
            data: json,
            contentType: 'application/json; charset=utf-8',
            success: function(data){ 
                //var message = data.Message; 
                alert(data);
                $('.CommentSection').html(data);
            }

And in my controller;

在我的控制器中;

    [ValidateInput(false)]
    public ActionResult jQueryAddComment(Comment comment)
    {
        CommentSection commentSection = new CommentSection();

        //ya da - ya da 
        // fill the commentsection object with data

        //then
        return PartialView("CommentSection", commentSection);

    }

However, when I get back to the page the success alert doesn't happen. Can anyone see the flaw in this logic?

但是,当我回到页面时,成功警报不会发生。谁能看出这个逻辑的缺陷?

回答by xandercoded

Your expecting JSONin the .Ajax POST, but in the ActionMethod your returning a PartialView?

JSON在 中期待.Ajax POST,但在 ActionMethod 中您返回一个PartialView?

Try:

尝试:

$.ajax({
   url: "/Home/jQueryAddComment",
   type: "POST",
   dataType: "html",
   data: json,
   success: function(data){ 
      //var message = data.Message; 
      alert(data);
      $('.CommentSection').html(data);
   }
}

回答by jwsample

Unless it was copied over wrong it appears you are missing some closing tokens.

除非它被错误地复制,否则您似乎缺少一些结束标记。

       $.ajax({
        url: "/Home/jQueryAddComment",
        type: "POST",
        dataType: "json",
        data: json,
        contentType: 'application/json; charset=utf-8',
        success: function(data){ 
            //var message = data.Message; 
            alert(data);
            $('.CommentSection').html(data);
            } //<-- added close for anonymous function
        }); //<--added close/semicolon for ajax function

Also, you are POSTing but it your action doesn't appear to have the [Post] attribute. When you run this in the debugger does a breakpoint on your action get hit?

此外,您正在发布,但您的操作似乎没有 [Post] 属性。当您在调试器中运行它时,您的操作上的断点是否会被击中?