asp.net-mvc - 如何从另一个 Controller 渲染部分内容

标签 asp.net-mvc

如果我有一个 HomeController 显示其索引 View ,我将如何继续让索引 View 从另一个 Controller 嵌入 UserControl?

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

<%@ 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>

这是其他 Controller 内容:

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

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

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

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

按此

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

可以工作,但它确实很难看。必须有更好的方法来嵌入来自另一个 Controller 的部分吗?

更新::找到解决方案

这是实现 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>

最佳答案

使用 ASP.NET MVC Futures 中的 Html.RenderAction 方法图书馆。

关于asp.net-mvc - 如何从另一个 Controller 渲染部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1348916/

相关文章:

c# - 将类添加到 ActionLink

ASP.NET MVC 认为我的虚拟目录是一个 Controller

javascript - Morris js 动态 ykeys

jquery - 在文本框上手动设置不显眼的验证错误

asp.net - 当 CustomError 设置为 "On"或 "RemoteOnly"时,运行状况监控不会记录错误

c# - Windows Azure 部署 - 未加载文件或程序集 'Newtonsoft.Json'

c# - 如何访问 ASP.NET Core 服务中的路由数据/值提供程序数据?

javascript - jsGrid 不会渲染 JSON 数据

javascript - 在Javascript部分分配剑道网格的数据源。 (Asp.net MVC-Razor 引擎)

javascript - View 未将模型传递给 Controller ​​ - ASP.Net MVC