Nếu tôi có HomeController hiển thị chế độ xem Chỉ mục của nó, tôi sẽ tiến hành như thế nào để có chế độ xem Chỉ mục được gắn một UserControl từ một Bộ điều khiển khác?Cách hiển thị partials từ một Bộ điều khiển khác
Dưới đây là một cái nhìn tại các nội dung của Home/Index Xem:
<%@ 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>
Dưới đây là nội dung OtherController:
public class OtherController : BaseController
{
private readonly IRepositoryContract<SomeType> repo = new SomeTypeRepository();
public ActionResult SomeAction()
{
IQueryable<SomeType> items = repo.GetAllItems();
return View("SomeAction", items);
}
}
này mang lại cho tôi một NullReferenceException từ Controller là không bao giờ được gọi bằng các Phương thức RenderPartial(). Thay đổi dòng sau
<% Html.RenderPartial("~/Views/OtherController/SomeAction.ascx"); %>
của thành viên này
<% Html.RenderPartial("~/Views/OtherController/SomeAction.ascx",((ViewResult) new OtherController().SomeAction()).ViewData.Model); %>
công trình, nhưng nó chắc chắn là xấu xí như địa ngục. Có phải là một cách tốt hơn để imbed partials từ bộ điều khiển khác?
Cập nhật :: Giải pháp phát hiện
Dưới đây là đoạn code sau khi thực hiện Adrian Grigore 's giải pháp: partials
<%@ 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>
Điều đó hoạt động tuyệt vời! Cảm ơn ngài. Tôi đã thay đổi <% Html.RenderPartial ("~/Views/OtherController/SomeAction.ascx"); %> line by <% Html.RenderAction ("SomeAction", "OtherController"); %> và nó hoạt động tự hỏi, gọi OtherController và hiển thị dữ liệu chính xác. –