Child actions are not allowed to perform redirect

2020-04-07 03:57发布

问题:

In _Layout.cshtml file I have following entry:

@Html.Action("LoadPagesStructure", "Page")

Inside PageController class, LoadPagesStructure methos looks following:

[ChildActionOnly] /* this attribute indicates that an action should not 
                     be invoked as a result of a user request (by url) */
public ActionResult LoadPagesStructure()
{         
    ViewModel.Pages = new List<string>() {"page1", "page2", "page3"};
    return View();
}

Finally, my LoadPagesStructure.cshtml view looks like below:

@inherits System.Web.Mvc.WebViewPage<dynamic>

<ul>
    @foreach (var page in View.Pages) {
    <li>        
        @Html.ActionLink(page, "Index", "Home")
    </li>
    }
</ul>

Unfortunately, an exception is thrown after execution:

System.InvalidOperationException: Child actions are not allowed to perform redirect actions.

What is the way of creating links to my pages dynamically ?

PS: I know that I can do this like that: <a href="@page">@page</a>. Nevertheless I think this is not the right way, because control of the routing is impossible here.

Regards

回答1:

I think you might need to return a PartialView for your LoadPagesStructure() action.

Try this:

[ChildActionOnly]
public ActionResult LoadPagesStructure()
{         
    ViewModel.Pages = new List<string>() {"page1", "page2", "page3"};
    return PartialView();
}