0

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 PartialView and 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>
timmack
  • 590
  • 2
  • 12
  • 43
  • You don't need a view to consume Ajax posts. – Control Freak Oct 05 '14 at 05:40
  • Is your controller being hit? Is the value of `com` valid or null? –  Oct 05 '14 at 05:41
  • @StephenMuecke Yes Im pretty sure that my controller is hit because if I'm going to remove the e.preventDefault() on the script it will return the partial view itself and its content, but what I want is to return the partialview within ajaxcom div of the view. – timmack Oct 05 '14 at 05:45
  • @ControlFreak Any idea? – timmack Oct 05 '14 at 05:48
  • You said the comment was not being saved so is the value of `com` valid in the controller? –  Oct 05 '14 at 05:49
  • @StephenMuecke Yes, the com CommentModel is valid in the controller because as I've said, if I remove the e.preventDefault() on the script it will return the partial view itself and its content with the new comment added. In contrary, it will not return the partial view in the ajaxcom div and the comment were not being saved as well. So what's wrong on it? – timmack Oct 05 '14 at 05:54
  • This is why you use JSON data as the response for your postback. – Control Freak Oct 05 '14 at 06:00
  • That's not relevant (the ajax method is using `$(this).serialize()`). Put a breakpoint on your controller and check. –  Oct 05 '14 at 06:01
  • @ControlFreak How do I do this? Can you give me sample script code, Thanks – timmack Oct 05 '14 at 06:02
  • Sure, look here: http://stackoverflow.com/questions/227624/asp-net-mvc-controller-actions-that-return-json-or-partial-html – Control Freak Oct 05 '14 at 06:05
  • @StephenMuecke I already tested my controller and it works fine it's just when I combined it with the ajax script and a partialview then the trouble started. I think you're being confused with the CreateViewModel, I guess. Would you like to take alook? – timmack Oct 05 '14 at 06:05
  • @timmack, You can use a partial view or JSON (although you should add `dataType: html,`. Have you tested your controller using the ajax script (or just without it)? –  Oct 05 '14 at 06:08
  • I tested my controller without ajax script and it works fine.thats why I suspected on my ajax script – timmack Oct 05 '14 at 06:14
  • Then put a breakpoint in your controller and test it WITH with the ajax script. Is `com` valid? –  Oct 05 '14 at 06:18
  • I put a breakpoint on the controller and I run it and I don't see any indication on my IDE or whatsoever or any highlights seen. I'm trying to understand now this json and still confusing for me how play with it on my controller. – timmack Oct 05 '14 at 06:29
  • @ControlFreak I looked at your thread about json do I really need to use ajax actionlink, what about if I just want to use a plain button? from this sample controller **public ActionResult SomeActionMethod() { return Json(new {foo="bar", baz="Blech"}); } ** How do I put my actual controller there? Still a bit confused. – timmack Oct 05 '14 at 06:35
  • No you don't need to use actionlink. You need to call that controller action in your jquery ajax call to return the json data and parse it – Control Freak Oct 05 '14 at 06:36
  • Using my controller based on the answers on that thread I see this inside the controller return Json(new {foo="bar", baz="Blech"}); but I want to return the partialview which is return PartialView("AddComments", vModel); How do I insert this on the return Json(new {???});? – timmack Oct 05 '14 at 06:47
  • Is this the right way? return Json(PartialView("AddComments", vModel)); – timmack Oct 05 '14 at 06:50

0 Answers0