开发者

Problem using RenderAction() with the current action

开发者 https://www.devze.com 2023-01-26 04:07 出处:网络
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 par

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号