无法将PartialView返回到jQuery.ajax调用

时间:2022-10-08 07:36:34

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.

我正在开发一个ASP.NET MVC应用程序,它在主页面上有3个部分(基于Razor引擎)。第一部分具有用户填充的搜索条件列表。第二个部分应该根据传入的数据显示ParameterParts列表。第三部分应该根据传入的数据显示规范列表。我需要调用Controller中的方法来填充我的第二和第三部分视图。

The issue:

  • Returning a PartialView causes the ajax call to match the error condition.
  • 返回PartialView会导致ajax调用与错误条件匹配。

  • Returning void matches the success condition but then I have nothing to populate parameterResults.
  • 返回void匹配成功条件但是我没有任何东西可以填充参数。

  • Returning json matches the success condition but then my partial view doesn't render anything.
  • 返回json匹配成功条件,但然后我的局部视图不呈现任何内容。

  • 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.
  • 如果我可以将我的部分视图转换为字符串并将其作为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)但是这需要我使用Nuget下载一个库,由于我们的公司防火墙,它在某种程度上不起作用。

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

所有三个部分的父视图(index.cshtml)的代码

<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):

第一部分代码(_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.

此代码使用dataToPass参数正确调用ParameterParts方法。

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?

我不包括第3部分,因为它与第2部分相同。如何使用上述方法更新我的部分?

2 个解决方案

#1


5  

 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.

dataType是您期望从服务器返回的数据类型。如果你要返回html,那不应该是json。

data is the data to be sent to the server.

data是要发送到服务器的数据。

Update:

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

您错过了#,您的选择器不正确。如果您的HTML是这样的:

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

your code should be this:

你的代码应该是这样的:

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

#2


1  

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

然后在客户端jquery ajax成功回调,只需简单地将返回的数据附加到你的dom中

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

#1


5  

 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.

dataType是您期望从服务器返回的数据类型。如果你要返回html,那不应该是json。

data is the data to be sent to the server.

data是要发送到服务器的数据。

Update:

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

您错过了#,您的选择器不正确。如果您的HTML是这样的:

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

your code should be this:

你的代码应该是这样的:

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

#2


1  

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

然后在客户端jquery ajax成功回调,只需简单地将返回的数据附加到你的dom中

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