[RESOLVED]How to use ajax script to prevent from postback view when saving records into the database?

I have a controller which I used to save records into the database. I noticed that everytime the I save a record the entire view will flicker or postback. So I researched and I realized that I need to use a PartialViewand
an 
AJAX script to avoid from view postback. So far, what I’ve got are the details below but somehow I encountered trouble using them. Using the details below, when you post a comment, the div element named"ajaxcom" in
the view where my initial comments are displayed will be gone and the comments were not even saved anymore into the database but instead I want to display my partial view into the ajaxcom div element after when you click the 
Post Comments button
so that the entire view will not postback and just automatically displays the new comments within the ajaxcom div element. So I suspected there must have been something wrong with my ajax script below. How do I fix this? and what am I been missing?…Thanks

AJAX Script:

$(function () {

            $("#addcomment").on("submit", function (e) {
               e.preventDefault();

                $.ajax({
                  url: this.action,

                  type: this.method,

                 data: $(this).serialize(),

                    success: function (data) {
                     // ajaxcom is the id of the div element where I want to display my partialview 
                        $("#ajaxcom").html(data);

                    }
                });
            });
        });

Controller:

[HttpPost]
    public  ActionResult AjaxComments(CommentModel com)
    {

                if (ModelState.IsValid)
                {
                    comrepository.InsertComment(com); //this is to insert the records
                }
                  var vModel = new CreateViewModel();

                vModel.Comments = comrepository.GetAllComments().ToList();

                // AddComments is my partialview
                return PartialView("AddComments", vModel);

    }

View:

@using (Html.BeginForm("AjaxComments", "Profile", FormMethod.Post, new { id = "addcomment" }))
 {
    <fieldset>
        <legend>CommentModel</legend>

        <div class="editor-label">
           <label for="name">Name</label>
        </div>
        <div class="editor-field">

       <input type="text" id="name" name="name" />
       <span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="comment">Post your Comment here:</label>
        </div>
      <div class="editor-field" style="margin-bottom:0px">
      <textarea id="comment" name="comment" style="width:500px;height:100px;resize:none"  aria-multiline="True"></textarea>
      <span class="field-validation-valid" data-valmsg-for="comment" data-valmsg-replace="true"></span>
        </div>

        <p>
             <input type="submit" value="Post Comments" name="butname" />   

        </p>

        <br />

    </fieldset>

 }
    <h2>Comments</h2>
     <br />

  <div id="ajaxcom"> <!-- Div element to be invoked by ajax script  -->

  <table id="mytable">  

  @foreach (var item in Model.Comments )
      {
    <tr >
        <td class="tdstyle" >

  <div style="font-weight:bold;">  @Html.DisplayFor(modelItem => item.name) </div> 

   <p class="comment more" style ="white-space: pre-line; margin-top:0px;margin-bottom:0px; border-radius: 4px 4px 4px 4px; max-width :500px; min-height :5px;  display :block; background-color: #CCCCFF">  @Html.DisplayFor(modelItem => item.comment) </p>
  <p style="margin-top:2px;margin-bottom:0px"> <input type="button" id="like" name="like" value="Like" style="color:blue;border:0px;background-color:inherit;cursor:pointer" /> <input type="button" class ="Reply" name="Reply" value="Replie(s)"  style="margin-bottom:0px;color:blue;border:0px;background-color:inherit;cursor:pointer" /></p>


        </td>       
    </tr>

    }

</table>
 </div>

Hi timmack,

Please add a new partial view to display the comment details (e.g. CommentDetail.cshtml).

<table id="mytable">  

  @foreach (var item in Model.Comments )
      {
    <tr >
        <td class="tdstyle" >

  <div style="font-weight:bold;">  @Html.DisplayFor(modelItem => item.name) </div> 

   <p class="comment more" style ="white-space: pre-line; margin-top:0px;margin-bottom:0px; border-radius: 4px 4px 4px 4px; max-width :500px; min-height :5px;  display :block; background-color: #CCCCFF">  @Html.DisplayFor(modelItem => item.comment) </p>
  <p style="margin-top:2px;margin-bottom:0px"> <input type="button" id="like" name="like" value="Like" style="color:blue;border:0px;background-color:inherit;cursor:pointer" /> <input type="button" class ="Reply" name="Reply" value="Replie(s)"  style="margin-bottom:0px;color:blue;border:0px;background-color:inherit;cursor:pointer" /></p>


        </td>       
    </tr>

    }

</table>
[HttpPost]
    public  ActionResult AjaxComments(CommentModel com)
    {

                if (ModelState.IsValid)
                {
                    comrepository.InsertComment(com); //this is to insert the records
                }
                  var vModel = new CreateViewModel();

                vModel.Comments = comrepository.GetAllComments().ToList();

                // AddComments is my partialview
                return PartialView("CommentDetail", vModel);

    }

Best Regards

Starain Chen

I would suggest you to use MVC ajax, instead of jquery ajax. You are using jquery ajax, which also works but there is some problem in the way you are calling i guess the url, and data are not correct.

Replace html forms with ajax forms and remove the javascript function. verify how it works.

@using (Html.BeginForm("AjaxComments", "Profile", FormMethod.Post, new { id = "addcomment" }))

@using (Ajax.BeginForm("AjaxComments", "Profile", new { id = "addcomment" }, new AjaxOptions { UpdateTargetId = "ajaxcom", HttpMethod = "POST", InsertionMode = InsertionMode.Replace }))

 

Leave a Reply