jqueryasp.net-coreasp.net-ajax

jQuery ajax functions doesn't work without error in my project


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>

Solution

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