Search code examples
ajaxasp.net-mvc-3asp.net-mvc-ajax

How to call partial view through ajax in mvc3


I need to call a partial view through ajax. I have tried the following, but I am not sure how to complete it.

$("#UserName").change(function () {
        var userid = $("#UserName").val();
        var ProvincialStateID = $("#State").val();
        var Hobbyid = $("#Hobby").val();
        var Districtid = $("#DistrictNames").val();
        var Homeid = $("#Hobbyhome_EstablishmentId").val();
        var urlperson = '@Url.Action("FetchPersonByUserName")';
        $.ajax({
            type: "POST",
            url: urlperson,
            data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
            success: function (data) { 
           //Dont know what to write here
        });
    });

Here is the function that I have written in my Controller:

 [HttpPost]
    public ActionResult FetchPersonByUserName(int userid,int stateid,int districtid,int homeid,int Hobbyid)
    {
      //Code to fetch the data in the partial using all parameters
      return PartialView("_LearnerAssociationGridPartial", list);
    }

When I click on a dropdown the ajax gets called and I want the function which is called through ajax to redirect it to the partial view. Please help me because currently I am not able to display my partial view


Solution

  • What you need is something like

    $.ajax({
       type: "POST",
       url: urlperson,
       data: { userid: userid, 
               stateid: ProvincialStateID, 
               hobbyid: Hobbyid, 
               districtid: Districtid, 
               homeid: Homeid },
        success: function (data) { 
              var result = data; 
              $('targetLocation').html(result);
        }
       });
    

    it is recomended to not use data straight from variable but you can. Now target location is where you want the result to be displayed to.

    See more information in here:

    http://api.jquery.com/jQuery.ajax/

    As to slow fetching data, try optimalize your query

    Update For nhibernate running slow, try http://www.hibernatingrhinos.com/products/nhprof which is nhibernate profiler, for paid version, or try sql profiler to see what is query is beeing executed, often you can get much more that you would expect and or really slow query due to complexity of the query.