Search code examples
jqueryasp.net-mvc-4partial-viewsgetjson

How to call partial view using JQUERY


I try to loadn partial view using ajax. But it gives me error as Internal char error. I debug the code then it call the action as well as also able to debug the the partial view but, after last line of partial view it gives me internal char error.

below is the partial view:

@model company.learn.data.Models.ProductViewModel
<div></div>

Action code is as follow:

  public ActionResult LoadProducts()
    {
        RepositoryProductManager m = new Repository.ProductManager();
        var p = m.RetrieveAllProducts();
        var l = p.Select(o => new ProductViewModel() { Cost = o.Cost, Description =    o.Description, Id = o.Id, ProductName = o.ProductName, ProductTypeName =   o.ProductType.Name, ProductTypeId = o.ProductTypeId }).ToList().FirstOrDefault();
        return PartialView("_LoadProducts",l);
     } 

jquery ajax call:

@section scripts
{
<script>
    $.getJSON('@Url.Action("LoadProducts","ProductManagement")', null, function (data)          {
        alert('f');
        //$('#ProductsDiv').html(data);
        alert('f');
    }
    ).error(function (e1, e2, e3) { alert(e3); });  //every time goes to alert this error.

   </script>

}

When i remove the DIV element from partial view and only keep first line (model binding) then it did not give me error but, whenevery i add any element into this view then it gives me error.

Please guide me for weird behavior.

thanks


Solution

  • You are using $.getJSON and in the controller you are returning a PartialView.

    Change the $.getJSON to ajax call and set dataType: "html".

    $.ajax({
        url: '/ProductManagement/LoadProducts',
        dataType: "html",
        success: function (data) {
            //$('#ProductsDiv').html(data);
        }
    });