我正在构建一个具有组件架构的 ASP.Net MVC 2 应用程序。有两种不同类型的组件:Elementary Components和 Layout Components ,它们具有关联的控制器操作来呈现局部视图,以及Layout Components,它们在特定布局中呈现其所有子组件(基本组件或再次布局)。
这是我的通用RenderComponent()操作方法,它采用组件 ID 并呈现适当的视图:
[ChildActionOnly]
public ActionResult RenderComponent(int id)
{
ComponentRepository repository = new ComponentRepository();
Component component = repository.GetComponent(id);
if (component.ControllerName != null && component.ViewName != null)
{
// render elementary component
return PartialView("Elementary", component);
}
else
{
// render layout
return PartialView(component.Layout.ViewName, component);
}
}
Elementary.ascx呈现一个基本组件:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.Component>" %>
<% Html.RenderAction(Model.ViewName, Model.ControllerName); %>
目前唯一存在的布局是VerticalLayout.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.Component>" %>
<%
foreach (var child in Model.ChildComponents()) {
%>
<div class="layout-container">
<% Html.RenderAction("RenderComponent", "Core", child.ID); %>
</div>
<%
}
%>
问题:
当我尝试使用三个关联的基本子组件呈现示例布局组件时,页面不会呈现。一些调试揭示了以下问题:
RenderComponent(5)
呈现布局视图。用于渲染布局中的第一个子组件,Html.RenderAction("RenderComponent", "Core", 1)
在视图中被调用。更进一步,我发现实际上RenderComponent(5)
是调用而不是RenderComponent(1)
!!
这显然会导致布局视图渲染本身的无限循环。
为什么会这样?我该如何解决?我的分层组件架构是否与 ASP.Net MVC 不兼容?您将如何在 ASP.Net MVC 中构建这样的系统?