Welcome to ZaiZheLe Developer Zone-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
8.3k views
in Technique[技术] by (71.8m points)

jquery - Update HTML.Partial after Post only ASP.NET MVC

I like only to update the @Html.Partial("_CommentSection") after Button type="submit" id="PostButton" is clicked by the user.

At the moment I reload the whole page to see the new comment. But I think its not nice to have it.

Is there a way to do it maybe and you can help me a bit more to come to my goal. Maybe with jquery - but I didn`t use this before and don't know how to do

I have in asp.net project a partial view of this code:

@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>


}

My View:

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

My Controller (update page after post is commented out)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use jquery and ajax call to get your partial view and update the only comment view on the screen instead of submitting and loading a whole form. I'm just giving you an idea. You need to work on this idea and expand it. Let me know if you need any help.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to ZaiZheLe Developer Zone-Open, Learning and Share
...