Yasir
Yasir

Reputation: 1625

Unable to return PartialView to a jQuery.ajax call

Background:

I am working on an ASP.NET MVC app that has 3 partials (based upon Razor engine) on the main page. The first partial has a list of search criteria that the user fills. The second partial is supposed to show the list of ParameterParts based upon the passed in data. The third partial is supposed to show the list of Specifications based upon the passed in data. I need to call methods in the Controller to populate my 2nd and 3rd partial views.

The issue:

Code for the parent View (index.cshtml) for all the three partials

<div class="prepend-top span-24 last" id="searchPage">
    <div class="span-24 last">
        @Html.Partial("_Search")
    </div>
    <div class="span-24 last" id="parameterResults">
        @Html.Partial("_ParameterParts")
    </div>
    <div class="span-24 last" id="searchSpecResults">
        @Html.Partial("_Specifications")
    </div>
</div>

Code for the first partial (_Search.cshtml):

 // Post the object to the server using jQuery
 $.ajax({
     url: '@Url.Action("ParameterParts")',
     type: 'POST',
     dataType: 'html',
     data: dataToPass,
     error: function (data) { alert('Something Went Wrong'); },
     contentType: 'application/json; charset=utf-8',
     success: function (data) {
         alert('Success P');
         $("parameterResults").html(data);
     }
 });

This code correctly calls the ParameterParts method with the dataToPass parameter.

Here is the code I am using for the controller method:

[HttpPost]
public ActionResult ParameterParts(CriteriaViewModel vm)
{
    List<ParameterPart> parameterParts = new List<ParameterPart>();

    //Some logic to populate parameterParts using the passed in object

    return PartialView("_ParameterParts", parameterParts);
}

Code for the 2nd partial:

@model IEnumerable<SmartPlex.Web.SmartPlex.ODataService.ParameterPart>

<table>
    <tr>
        <th>
            Part Number
        </th>
        <th>
            Description
        </th>
    </tr>
    @if (Model != null)
    {
        foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.PartNumber)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Description)
                </td>

            </tr> 
         }                       
    }
</table>

I am not including the 3rd partial as it is the same as the 2nd one. How can I update my partials using the above method?

Upvotes: 3

Views: 9700

Answers (2)

B Z
B Z

Reputation: 9463

 dataType: 'dataToPass',
 data: json,

dataType is the datatype you are expecting back from the server. Which shouldn't be json if you are returning html.

data is the data to be sent to the server.

Update:

You are missing the #,your selector is incorrect. If your html is this:

<div class="span-24 last" id="parameterResults">
  @Html.Partial("_ParameterParts")
</div>

your code should be this:

 $("#parameterResults").html(data);

Upvotes: 5

labroo
labroo

Reputation: 2961

you dont need a separate library to render partial views as string. create a extension method like this:

 public static class RazorViewToString  
{
    public static string RenderRazorViewToString(this Controller controller, string viewName, object model)
    {
        if (controller==null)
        {
            throw new ArgumentNullException("controller", "Extension method called on a null controller");
        }

        if (controller.ControllerContext==null)
        {
            return string.Empty;
        }

        controller.ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

}

then inside your controller you can use this as

return new JsonResult {Data = this.RenderRazorViewToString("partialViewName", model)};

then on the client jquery ajax success callback, just simple append the returned data in your dom

http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/

Upvotes: 1

Related Questions