I'm building an ASP.Net MVC 2 application with a component architecture. There are two different types of components: Elementary Components, which have an associated controller action rendering a partial view, and Layout Components, which render all their child components (Elementary Components or again Layouts) in a certain layout.
Here is my generic RenderComponent() action method, which takes a component ID and renders the appropriate view:
[ChildActionOnly]
public ActionResult RenderComponent(int id)
{
ComponentRepository repository = new ComponentRepository();
Component component = reposit开发者_JS百科ory.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 renders an elementary component:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.Component>" %>
<% Html.RenderAction(Model.ViewName, Model.ControllerName); %>
Currently the only existing layout is the 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>
<%
}
%>
The Problem:
When I tried to render an example layout component with three associated elementary child components, the page wouldn't render. Some debugging revealed the following problem:
RenderComponent(5)
renders the layout view.
For rendering the first child component in the layout, Html.RenderAction("RenderComponent", "Core", 1)
is called in the view. Stepping further, I discovered that in effect RenderComponent(5)
is called instead of RenderComponent(1)
!!
This obviously results in an infinite loop of the layout view rendering itself.
Why is this happening? How can I fix it? Is my hierarchical component architecture incompatible with ASP.Net MVC? How would you build such a system in ASP.Net MVC?
OK, my bad... Of course it has to be <% Html.RenderAction("RenderComponent", "Core", new { id = child.ID}); %>
in VerticalLayout.ascx.
精彩评论