0

I want to load data to a div by id commentList by Ajax function. I need to send the data to an action named CreateComment by a form tag using Ajax. After creating the comment I need to load the data in div by id commentList again. but the form tag doesn't send the data and also the data doesn't load to the div commentList after loading the view.

Here is the form tag:

<form class="active" asp-controller="Product" asp-action="CreateComment" id="review_form"
      data-ajax="true" data-ajax-method="post" data-ajax-mode="replace"
      data-ajax-update="#listcomment" data-ajax-success="Success">
    <input type="hidden" name="comment.ProductId" value="@Model.ProductId" />
    <label>
            متن
    </label>
    <textarea name="comment.Comment" id="comment_Comment"></textarea>
    <button class="form-btn" type="submit">ثبت نظر</button>
</form>

This is the action CreateComment:

 public IActionResult CreateComment(ProductComment comment)
 {
     comment.CreateDate = DateTime.Now;
     comment.IsDelete = false;
     comment.UserId = _userService.GetUserIdByUserName(User.Identity.Name);

     _productService.AddComment(comment);

     return View("ShowComments", _productService.GetProductComments(comment.ProductId));
 }

This is the div that I want to load the data by Ajax:

 <div class="small-12 medium-5 large-5 columns" id="commentList">
     <div class="fr-border"></div>
 </div>

This is the ajax function:

<script src="/js/jquery.unobtrusive-ajax.min.js"></script>
<script>
    function Success() {
        $("#comment_Comment").val("");
    }
    
    $(function () {
        $("#commentList").load("/Product/ShowComments/@(Model.ProductId)");
    });
</script>
1
  • I think ShowComments is your partial view that you are returning when a comment is inserted. But based on your codes it never gets called. If you need to load the partial view when the insert process is finished, you need to do it manually. My suggestion is: instead of using <form> tag, create a method that calls the API through the AJAX, and then renders the partial view in the the commentList when the call is successful Commented Nov 13, 2024 at 16:02

1 Answer 1

0

If your ShowComments is a partial view, you can use return PartialView and Html.PartialAsync method to call it. Here is an example for your reference:

Controller:

public IActionResult CreateComment(ProductComment comment)
 {
     comment.CreateDate = DateTime.Now;
     comment.IsDelete = false;
     comment.UserId = _userService.GetUserIdByUserName(User.Identity.Name);

     _productService.AddComment(comment);

     return PartialView("ShowComments", _productService.GetProductComments(comment.ProductId));
 }

ShowComments.cshtml:

@model IEnumerable<ProductComment>

    @foreach (var comment in Model)
    {
        <div class="comment">
            <p>@comment.Text</p>
            <small>@comment.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")</small>
        </div>
    }

Index.cshtml:

<form id="commentForm" method="post" asp-action="CreateComment" asp-controller="Product">
    <input type="hidden" name="ProductId" value="101" />
    <textarea name="Text" placeholder="add comment"></textarea>
    <button type="submit">ثبت نظر</button>
</form>
<div id="commentList">
    @await Html.PartialAsync("ShowComments", (object)Model)

</div>

@section Scripts {
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#commentForm').on('submit', function (event) {
                event.preventDefault(); 

                $.ajax({
                    url: '@Url.Action("CreateComment", "Product")',
                    type: 'POST',
                    data: $(this).serialize(),
                    success: function (response) {
                        $('#commentList').html(response); 
                    },
                    error: function (xhr, status, error) {
                        console.error('Error:', error);
                    }
                });
            });
        });
    </script>
}

After adding the sample comment:

enter image description here

For more information about partial views, please refer to this link.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your guidance, but I want to use ajax in my project. and it seems that all my jquery ajax codes are inaccessible. Not showing the error is confusing me. So do have any suggestion to solve this problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.