Search code examples
asp.net-mvc-3jqueryrenderpartial

Render Partial View using Jquery Ajax with variable data


I have already read this post, but I am not sure know to make it work taking data from the user. Here is the ajax jquery I am using. I know (or at least think) that this cant render a partial. But it works all the way until the render fails. I thought it may be helpful to have.

 $.ajax(
     {
         type: 'POST',
         contentType: 'application/json; charset=utf-8',
         data: "{'test':" + "'" + dateText + "'}",
         dataType: 'json',
         url: 'Site/Grab/',
         success: function (result) {
         alert('Success');
         },

         error: function (error) {
            alert('Fail');
         }
      });

Here is my controller

[HttpPost]
    public ActionResult Grab(string test)
    {
        DateTime lineDate= Convert.ToDateTime(test);
        List<Info> myInfo= GameCache.Data(lineDate);
       return PartialView("_PartialView", myInfo);
    }

Solution

  • Okay, couple of things to try:

    1) dataType is the expected result of the ajax call. In your case, your sending JSON, but receiving HTML. The content-type parameter specifies the request, which you have (and what you have is correct). So the data type should be:

    dataType: 'html',
    

    2) You need to serialize the JSON. Try grabbing the lightweight JSON library and stringify'ing:

    var test = { test: 'testvalue' };
    $.ajax {
       ...
       data: JSON.stringify(test),
       ...
    });
    

    Much easier than trying to coerce a JSON string with quoatations. Create a regular JS variable, then stringify it.

    The rest of your code looks fine.

    If it's a problem with the HTML/markup of the partial view itself, run in debug mode and Visual Studio should stop on the line in the markup that is causing the problem.

    Bonus Hint: ASP.NET MVC 3 includes built-in JSON model binding. So you can create a basic POCO that matches the fields of your JSON object, then accept it as a strongly-typed object in the action method:

    [HttpPost]
    public ActionResult Grab(MyJsonObject obj) 
    {
       DateTime lineDate= Convert.ToDateTime(obj.test);
       List<Info> myInfo= GameCache.Data(lineDate);
       return PartialView("_PartialView", myInfo);
    }
    

    Since your only sending one parameter, it's overkill - but if you have more than 2 then it's worthwhile using a JSON POCO.