Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Returning a PartialView causes the ajax call to match the error condition.
  • Returning void matches the success condition but then I have nothing to populate parameterResults.
  • Returning json matches the success condition but then my partial view doesn't render anything.
  • It seems that things will work if I can convert my partialview to a string and return it as json (http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views) but this requires me to download a library using Nuget, which somehow doesn't work due to our corporate firewall.

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?

like image 252
Yasir Avatar asked Dec 27 '25 16:12

Yasir


2 Answers

 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);
like image 146
B Z Avatar answered Dec 30 '25 07:12

B Z


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/

like image 42
labroo Avatar answered Dec 30 '25 06:12

labroo