I am trying to recreate an example from Chapter-5 of book Pro Asp.net MVC2. But as soon as I add Menu code server stops working. Any Problem with the code?
public class NavController : Controller
{
private IProductRepository productsRepository;
public NavController(IProductRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult Menu()
{
Func<string, NavLink> makeLink = categoryName => new NavLink
{
Text = categoryName ?? "Home",
RouteValues = new RouteValueDictionary( new {
controller = "Products", action = "List", category = categoryName, page = 1
})
};
List<NavLink> navLinks = new List<NavLink>();
navLinks.Add(makeLink(null));
var categories = productsRepository.Products.Select(x => x.Category);
foreach (string categoryName in categories.Distinct().OrderBy(x => x))
navLinks.Add(makeLink(categoryName));
return View(navLinks);
}
}
Menu.cshtml
@model IEnumerable<SStore.WebUI.Models.NavLink>
@foreach (var link in Model)
{
Html.RouteLink(link.Text, link.RouteValues);
}
If I remove this line from my master page then server works
@{
Html.RenderAction("Menu", "Nav");
}
otherwise getting this error

Html.RenderAction("Menu", "Nav");: That’s horrible recursion:Nav/Menuwhich rendersNav/Menuwhich rendersNav/Menu, …, until you run out of stack and your web server blows 🙂When you render a child action like this ensure it has no master or the master’s gonna rerender it again and again and again, …. So modify this view (
~/Views/Nav/Menu.cshtml) like this:Let me explain:
The example you saw in the book was using the WebForms view engine. In this view engine you have
.aspx(views) and.ascx(partials). I suppose that in the book they were usingMenu.ascxwhich by default has no master because it is a partial.In Razor there is no longer such distinction. You simply have views: .cshtml pages. It is up to you to control whether they have a master or not. There are different ways. One is what I showed previously, another is to
return PartialView(navLinks)inside the child action.