【问题标题】:Update HTML.Partial after Post only ASP.NET MVC仅发布 ASP.NET MVC 后更新 HTML.Partial
【发布时间】:2021-04-17 20:34:55
【问题描述】:

我只喜欢在用户单击 Button type="submit" id="PostButton" 后更新 @Html.Partial("_CommentSection")。

目前我重新加载整个页面以查看新评论。但我认为拥有它并不好。

有没有办法做到这一点,你可以帮助我更多地实现我的目标。 也许用 jquery - 但我以前没用过,也不知道该怎么做

我在 asp.net 项目中有这段代码的部分视图:

@model MyProject.Models.Home

@foreach (var comment in MyProject.Controllers.HomeController.GetAllComments(Model.Id))
{
    <br />
    <div>
        <div>
            <a>
                @MyProject.Controllers.HomeController.GetUserName(comment.UserId)
            </a>
            added a comment -
            <span>
                <time>@comment.CommentCreated.ToString()</time>
            </span>
            <span id="edit-delete-comment">
                @using (Html.BeginForm("DeleteComment", "Home"))
                {
                    @Html.AntiForgeryToken()

                    if (MyProject.Controllers.HomeController.CheckIfUserIsCreator(User.Identity.Name, comment.CommentId))
                    {
                        if (!MyProject.Controllers.HomeController.CheckDateOfComment(comment.CommentId))
                        {
                            <div class="form-actions no-color">
                                @Html.Hidden("returnUrl", this.Request.RawUrl)
                                @Html.Hidden("CommentId", comment.CommentId)
                                <input type="submit" value="Delete" class="t" />
                            </div>
                        }
                    }

                }
            </span>

        </div>
        <br />
        <div>
            <p>
                @comment.CommentText
            </p>
        </div>
    </div>
    <hr />
}

@using (Html.BeginForm("CreateComment", "Home", FormMethod.Post, null))
{
    @Html.AntiForgeryToken()

    <div class="mt-5 d-flex flex-row">
        @Html.Hidden("returnUrl", this.Request.RawUrl)
        @Html.Hidden("HomeId", Model.Id)
        <textarea class="form-control" name="CommentText"></textarea>

        <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button>

    </div>


}

我的观点:

<div id="partial-update">
    @Html.Partial("_CommentSection")
</div>

我的控制器(帖子被注释掉后更新页面)

[HttpPost]
[AllowOnlyOneRequest]
[ValidateAntiForgeryToken]
public void CreateComment([Bind(Include = "CommentId,CommentText,CommentCreated,UserId,HomeId")] Comment comment, string returnUrl, int HomeId)
{
    if (ModelState.IsValid)
    {
        comment.CommentCreated = DateTime.Now;
        comment.UserId = db.Users.FirstOrDefault(i => i.UserEmail == User.Identity.Name).UserId;
        comment.HomeId = HomeId;

        db.Comments.Add(comment);
        db.SaveChanges();
        //return Redirect(returnUrl);
    }

    //return Redirect(returnUrl);
}

【问题讨论】:

    标签: jquery asp.net asp.net-mvc partial-views


    【解决方案1】:

    您可以使用 jquery 和 ajax 调用来获取部分视图并更新屏幕上唯一的评论视图,而不是提交和加载整个表单。我只是给你一个想法。你需要研究这个想法并扩展它。如果您需要任何帮助,请告诉我。

        $.ajax({
                        type: "POST",
                        URL: "/Home/CreateComment",
                        dataType: 'html',
                        data:JSON.stringify({
                           comment : $("name=['CommentText']").val(),
                           HomeId : $("name=['HomeId']").val()
                        }}
                        success: function (result) {
        
                            $('#Your Div where you want to append your partial comment').html(result);
                        },
                        error: function (error) {
                            //Handle error here
                        }
                    });
    
    Create a model on the ASP.NET side :
    
        public Comment{
             public string Comment {get; set;}
             public string HomeId {get;set;
        }
    Use this in a controller.
    
        CreateComment([HttpBody]Comment comment){
        comment.CommentCreated = DateTime.Now;
                comment.UserId = db.Users.FirstOrDefault(i => i.UserEmail == User.Identity.Name).UserId;
                comment.HomeId = comment.HomeId;
        
                db.Comments.Add(comment);
                db.SaveChanges();
        return PartialView("_CommentSection",comment)
        }
    

    检查这个新代码

        @model MyProject.Models.Home
    
        <div class="comments">
            @foreach (var comment in MyProject.Controllers.HomeController.GetAllComments(Model.Id))
            {
                <br />
                <div>
                    <div>
                        <a>
                            @MyProject.Controllers.HomeController.GetUserName(comment.UserId)
                        </a>
                        added a comment -
                        <span>
                            <time>@comment.CommentCreated.ToString()</time>
                        </span>
                        <span id="edit-delete-comment">
                            @using (Html.BeginForm("DeleteComment", "Home"))
                            {
                                @Html.AntiForgeryToken()
    
                                if (MyProject.Controllers.HomeController.CheckIfUserIsCreator(User.Identity.Name, comment.CommentId))
                                {
                                    if (!MyProject.Controllers.HomeController.CheckDateOfComment(comment.CommentId))
                                    {
                                        <div class="form-actions no-color">
                                            @Html.Hidden("returnUrl", this.Request.RawUrl)
                                            @Html.Hidden("CommentId", comment.CommentId)
                                            <input type="submit" value="Delete" class="t" />
                                        </div>
                                    }
                                }
    
                            }
                        </span>
    
                    </div>
                    <br />
                    <div>
                        <p>
                            @comment.CommentText
                        </p>
                    </div>
                </div>
                <hr />
            }
        </div>
    
    
    
    <div class="mt-5 d-flex flex-row">
        @Html.Hidden("returnUrl", this.Request.RawUrl)
        @Html.Hidden("HomeId", Model.Id)
        <textarea class="form-control" name="CommentText"></textarea>
    
        <button class="btn btn-secondary btn-block mt-2 post-btn" type="button" id="PostButton">Post</button>
    
    </div>
    
    <script>
        $(document).ready(function () {
            $('#PostButton').click(function () {
                let comment = $('[name="CommentText"]').val();
                let homeId = $('[name="HomeId"]').val();
                let obj = {
                    Comment: comment,
                    HomeId : homeId
                    }
                $.ajax({
                    type: "POST",
                    URL: "/Home/CreateComment",
                    dataType: 'html',
                    data:JSON.stringify({
                       obj
                    }),
                    success: function (result) {
                        $('.comments').append(result);
                    },
                    error: function (error) {
                        //Handle error here
                    }
                });
            })
            
        })
    </script>
    

    【讨论】:

    • 谢谢,看起来很酷。但以前从未使用过ajax。我需要在哪里放置 ajax 代码以及必须插入哪个 div
    • Ajax 代码将在您的剃须刀代码之后显示。这是一个 javascript 代码,因此您需要提供 标记并在文档就绪函数中编写 ajax 代码。当您单击添加注释按钮时,您将使用 ajax 调用调用控制器方法,并且该控制器方法将返回部分视图。因此,如果成功获取所有内容,您将获得 HTTP 200 OK 响应,并且响应将在 ajax 调用的成功方法中可用,您需要将该响应附加到要显示评论的 div。
    • learnrazorpages.com/razor-pages/ajax/form-post你可以参考这个页面。
    • 现在我明白了,谢谢。但是还是有一个问题。如果我提交帖子,ActionResult CreateComment 将返回return PartialView("_CommentSection", home);。发布后,我真的得到了这个部分的观点。我将从Home/Details/1重定向到Home/CreateComment
    • 我认为问题出在 Html.BeginForm using (Html.BeginForm("CreateComment", "Home",...。但老实说,我不知道我需要用什么来替换 Html.BeginForm
    猜你喜欢
    • 2016-11-02
    • 2012-01-19
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多