Ashar Ashar - 3 months ago 14
jQuery Question

Reload partial view using $.load shows json

With reference to this tutorial I am using below code to show data in partial view AllWS

$.get("/Home/GetAllWS", function (json)
{
var strHtml = "";
$.each(json, function(i, wsdata)
{
strHtml = strHtml + "<div class='col-sm-4'>" +
"<p>" + wsdata.Title + "</p>" +
"</div>";
});

$('#allwsdiv').append(strHtml);
})

<div class="row" id="allwsdiv"></div>

// under index view ( calling above partial view)
<div id="allws">
@Html.Partial("AllWS")
</div>


This is working fine except when I try to reload view after adding an item success using $.load the div shows me json data in in browser.What I am missing.What is the correct way to reload partial view

//Item adding success
success: function (response) {
//Reload Partial view to fetch latest added records
$('#allws').load("@Url.Action("GetAllWS")");

alert('success');
},

Answer

Looks like your GetAllWS method return JSON data. You cannot use $.load method with that! $.load will replace the innerHTML of the jQuery selector with the response data coming back. That means you should use $.load when you are calling an action method which returns HTML markup (View Result usually)

I suggest you wrap the method which gets all items to a method and call that method in your success handler.

function loadAll()
{ 
    $.get("/Home/GetAllWS", function (json)
    {
        var strHtml = ""; 
        $.each(json, function(i, wsdata)
        {
            strHtml = strHtml + "<div class='col-sm-4'>" +
                       "<p>" + wsdata.Title + "</p>" +
                       "</div>";
        });
        $('#allwsdiv').append(strHtml);
    })
}

And call this method as needed. May be in document ready event and the success handler of your add item method

$(function(){
  loadAll();

  $("#addBtn").click(function(e){
     e.preventDefault();

     //your ajax call here
      $.ajax({
      // your existing code here
        ,success : function(response){
          loadAll();
        };
     });
  });

});

You might also consider sending the one new item in JSON format from the action method you are calling to add the new item. In that case, you do not need to call the loadAll method again. You just need to parse the json response coming back and append it to the existing container div(#allwsdiv)