ASP.NET MVC StackOverflowException从布局中的xml加载动态菜单

我尝试在我的布局中放置一个动态菜单(从xml加载),但我在PartialController.cs / MainMenu()中有一个StackOverflowException

我不明白为什么我的代码抛出StackOverflowException,因为我没有循环(或者我没有看到它!)。

Layout.cshtml:

....  .... 

MainMenu.cshtml:

 @model Geosys.BoT.Portal.POC.Business.Menu @foreach (var item in Model.Nodes) { 
  • @item.Name
      @foreach (var subItem in item.Links) {
    • @Html.ActionLink(subItem.Name, subItem.Action, subItem.Controller)
    • }
}

PartialController.cs:

 [ChildActionOnly] public ActionResult MainMenu() { var menu = new Menu { Nodes = new List() }; var xmlData = System.Web.HttpContext.Current.Server.MapPath("~/Content/navigation.xml"); if (xmlData == null) { throw new ArgumentNullException("xmlData"); } var xmldoc = new XmlDataDocument(); var fs = new FileStream(xmlData, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); var xmlnode = xmldoc.GetElementsByTagName("node"); for (var i = 0; i <= xmlnode.Count - 1; i++) { var xmlAttributeCollection = xmlnode[i].Attributes; if (xmlAttributeCollection != null) { var nodeMenu = new NodeMenu { Name = xmlAttributeCollection["title"].Value, Links = new List() }; if (xmlnode[i].ChildNodes.Count != 0) { for (var j = 0; j < xmlnode[i].ChildNodes.Count; j++) { var linkMenu = new LinkMenu(); var xmlNode = xmlnode[i].ChildNodes.Item(j); if (xmlNode != null) { if (xmlNode.Attributes != null) { linkMenu.Name = xmlNode.Attributes["title"].Value; linkMenu.Action = xmlNode.Attributes["action"].Value; linkMenu.Controller = xmlNode.Attributes["controller"].Value; linkMenu.Key = xmlNode.Attributes["key"].Value; nodeMenu.Links.Add(linkMenu); } } } } menu.Nodes.Add(nodeMenu); } } return View(menu); } 

navigation.xml:

        

编辑:这是exception的细节(没有StackTrace):

System.StackOverflowException未处理mscorlib.dll中发生未处理的“System.StackOverflowException”类型exception

{无法计算表达式,因为当前线程处于堆栈溢出状态。}

在Call Stack中,我看到“Html.RenderAction(”MainMenu“,”Partial“)行;” 经常打电话,但我不知道为什么。

这里有一个无限循环。 问题是您在布局中执行此操作:

 @Html.RenderAction("MainMenu", "Partial"); 

然后在你的行动中你这样做:

 return View(menu); 

当您调用return View()将呈现您的视图,包括您的布局。 所以你的布局然后再次呈现你的@Html.RenderAction(...) …它调用你的View()…呈现你的布局……等等等..等等。

您可以通过返回不呈现布局的PartialView()或通过将Layout设置为Null的视图进行渲染来解决此问题。 这是View()PartialView() ,Layout渲染之间的主要区别。