如何从另一个Controller渲染部分

Mat*_*ron 9 asp.net-mvc

如果我有一个HomeController显示其索引视图,我将如何进行索引视图嵌入来自另一个控制器的UserControl?

以下是主页/索引视图的内容:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
    <%=Resources.Global.HomeTitle %>
</asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
    <p><%=Resources.Global.HomeIndex %></p>

    <h3>Partial title</h3>
    <% Html.RenderPartial("~/Views/OtherController/SomeAction.ascx"); %>

</asp:Content>
Run Code Online (Sandbox Code Playgroud)

这是OtherController的内容:

public class OtherController : BaseController
{
    private readonly IRepositoryContract<SomeType> repo = new SomeTypeRepository();

    public ActionResult SomeAction()
    {
        IQueryable<SomeType> items = repo.GetAllItems();
        return View("SomeAction", items);
    }
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个NullReferenceException,因为RenderPartial()方法永远不会调用Controller.更改以下行

<% Html.RenderPartial("~/Views/OtherController/SomeAction.ascx"); %>
Run Code Online (Sandbox Code Playgroud)

这样

<% Html.RenderPartial("~/Views/OtherController/SomeAction.ascx",((ViewResult) new OtherController().SomeAction()).ViewData.Model); %>
Run Code Online (Sandbox Code Playgroud)

工作,但它肯定是丑陋的地狱.必须有更好的方法来嵌入来自另一个控制器的部分?

更新::找到解决方案

以下是实施Adrian Grigore解决方案后的代码:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="Microsoft.Web.Mvc"%>

    <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
        <%=Resources.Global.HomeTitle %>
    </asp:Content>

    <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
        <h2><%= Html.Encode(ViewData["Message"]) %></h2>
        <p><%=Resources.Global.HomeIndex %></p>

        <h3>Partial title</h3>
        <% Html.RenderAction("SomeAction","OtherController"); %>

    </asp:Content>
Run Code Online (Sandbox Code Playgroud)

Adr*_*ore 5

使用ASP.NET MVC Futures库中的Html.RenderAction方法.