【问题标题】:Not able to update the comment module on the mvc view using ajax call without refreshing the page无法在不刷新页面的情况下使用 ajax 调用更新 mvc 视图上的评论模块
【发布时间】:2013-03-31 11:45:10
【问题描述】:

这对我来说是一个检查和配对的情况...... 我正在使用 mvc 3。 我正在尝试在单个视图上创建一个帖子和评论模块。下面是视图和控制器的代码。我能够加载帖子和所有 cmets,但是一旦我通过 AJAX 调用添加新评论,它就会保存到数据库中的正确表中,但我不明白如何在不刷新页面的情况下更新它。 .

//model
public class PostViewModel
{
   public bool? IsActive
    { get; set; }

   public string PostDescription
    { get; set; }

   ...

    public List<PostCommentModel> objPostCommentInfo { get; set; }
}

//Post Controller

 DBEntities1 db = new DBEntities1();

    public ActionResult Index(int ID)
    {

        int id = Convert.ToInt32(ID);
        PostViewModel objPostViewModel = new PostViewModel();
        List<PostViewModel> lstobjPostViewModel = new List<PostViewModel>();

        PostCommentModel objPostCommentModel;
        List<PostCommentModel> lstobjPostCommentModel = new List<PostCommentModel>();

        var objPost = (from x in db.PostInfoes 
                        where x.PostId  == id
                        select x).ToList();

        var objPostComment = (from y in db.PostCommentInfoes  
                               where y.PostId  == id
                               orderby y.CommentId  descending
                               select y).ToList();

        foreach  (var x in objPost)
        {

            objPostViewModel.PostID = x.PostId;
            objPostViewModel.IsActive = x.IsActive;
            objPostViewModel.PostTitle = x.PostTitle;
            objPostViewModel.PostDescription = x.PostDescription;
            lstobjPostViewModel.Add(objPostViewModel);
        }

        foreach (var y in objPostComment)
        {
            objPostCommentModel = new PostCommentModel();
            objPostCommentModel.PostId  = y.PostId;
            objPostCommentModel.IsActive  = y.IsActive;
            objPostCommentModel.CommentBody = y.CommentBody;
            lstobjPostCommentModel.Add(objPostCommentModel);
        }
        objPostViewModel.objPostCommentInfo = lstobjPostCommentModel;
        return View(lstobjPostViewModel);
    }

  //view
  @model IEnumerable<MVCProjectModels.PostViewModel>

<table border="1">
 @foreach (var item in Model)
 {    
    <tr>
        <td>
            <text>Created By:</text>
            @Html.DisplayFor(modelItem => item.PostDescription)
        </td>
        <td rowspan="2">
            @Html.DisplayFor(modelItem => item.PostDescription)
        </td>
    </tr>
    .....
  }
 </table>
 <table>
 <tr>
    <td>
        <textarea cols="10" rows="5" id="txtComment"></textarea>
    </td>
  </tr>
  <tr>
    <td>
        <input id="btnPostComment" type="button" value="Post Comment" />
    </td>
 </tr>
 </table>
 <table border="1">
 @foreach (var item1 in Model)
 {
    foreach (var item2 in item1.objPostCommentInfo)
    {    
    <tr>
        <td colspan="2">
            @Html.DisplayFor(modelItem => item2.CommentBody)
        </td>
    </tr>
    }
  }
 </table>

//Ajax 调用来更新评论(cmets 被保存到数据库,但我无论如何都找不到在 UI 或视图上更新它)

       <script type="text/javascript">

       $("#btnPostComment").click(function () {
       var commentBody = $("#txtComment").val();
       postComment(commentBody);
       });
       function postComment(commentBody) {
       $.ajax({
       url: "/Post/postComment", // this controller method calls a store procedure to insert the new comment in the database.
          type: 'POST',
          data: {
              Comment: commentBody,
              ID: 6
          },
          success: function (result) {

          },
          error: function () {
              alert("error");
          }
        });
        }
        </script>

如果我在上述模块中犯了任何重大设计错误,请告诉我。我是 mvc 的新手,所以只是试图通过阅读一些书籍和文章来做到这一点,所以不确定这是否是实现这种结果的正确方法。谢谢

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3 jquery entity-framework-4


    【解决方案1】:

    您可以在 AJAX 调用的成功回调中将新的注释文本 .prepend() 到 cmets 表中:

    success: function (result) {
        // give your comments table a class="comments" so that the following
        // selector is able to match it:
        $('table.comments').prepend(
            $('<tr/>', {
                html: $('<td/>', {
                    text: commentBody
                })
            })    
        );
    }
    

    【讨论】:

    • 如果我这样做......在页面回发之后,是否会有 2 个相同的 cmets......因为页面加载我正在绑定数据库中的所有 cmets..
    • OnPageLoad 仅在最初加载 DOM 时调用一次。
    【解决方案2】:

    您需要为表格命名以便于参考:

    <table border="1" id="postList">
    

    在您看来,您正在编写用户名&lt;text&gt;Created By:&lt;/text&gt;,但我在模型中没有看到。因此,假设它保存在会话中,或者您可以在控制器中检索它,您可以执行以下操作:

    public ActionResult PostComment(YourModel input){
        // everything went well
        // you get this from a session or from the database
        var username = "the creator";
        return Json(new { success = true, username});
    } 
    

    在您的 ajax 调用的 success 上:

    success: function (result) {
        if (result.success) {
            $("#postList").append('<tr><td><text>Created By:</text>' +
                result.username + '</td><td rowspan="2">' +
                commentBody + '</td>');
        </tr>
        }
    }
    

    如果不是连接从template 读取的tr 字符串并插入必要的值,那将会很酷。或者您可以使用其他工具(例如敲除)在客户端进行绑定。但这是我猜的另一个问题。

    【讨论】:

    • 是的..我很抱歉我在模型中设置了许多值...只是删除它们以减少问题大小..但是是的,我从 db..I我没有在 cookie 中设置它...这个模块中没有错误..但是我没有找到通过 AJAX 调用显示存储到数据库的 cmets 的方法..如果我刷新页面一切都很好..
    • 好的,那么我建议的代码适合您的场景。你试过了吗,还有其他问题吗?
    • 是的,我理解您的代码....但是如果我点击刷新会发生什么.. 会有 2 个相同的 cmets 吗???因为我在后控制器上获取 cmets 索引 actionresult() ..
    • 不会,因为当您调用首先呈现视图的方法时,您的视图将完全刷新。
    猜你喜欢
    • 2017-06-12
    • 2022-01-21
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    相关资源
    最近更新 更多