【问题标题】:Return a PartialView from $.Ajax Post从 $.Ajax Post 返回一个 PartialView
【发布时间】:2010-08-16 01:30:34
【问题描述】:

我有以下代码;

        $.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);
            }

在我的控制器中;

    [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);

    }

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

【问题讨论】:

  • 对帖子的当前反应是什么?使用 Firebug 和/或 Fiddler 检查响应。

标签: asp.net-mvc jquery


【解决方案1】:

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

试试:

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

【讨论】:

  • 这很好。我返回了一个 json 对象,但 data.message 为空
  • 是的,看起来您可能只是在返回 html,而 Javascript 期待 JSON Object...
  • 如果我返回 Json 然后提醒这个 window.alert(data) 我得到对象。那么我现在如何获取对象中的 html。
  • 只需重新阅读您的答案,数据类型就是问题所在。谢谢
  • 您必须在脚本中将dataType:json 更改为dataType:"html",因为您从ActionMethod 返回的内容是HTML 而不是JSON Object
【解决方案2】:

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

       $.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

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

【讨论】:

  • 对不起,结束标记是正确的,我只是没有复制整个函数
  • jQueryAddComment 上的断点是否在调试器中命中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
相关资源
最近更新 更多