简体   繁体   中英

Pro Asp.net mvc 2: Problem in example

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/Menu which renders Nav/Menu which renders Nav/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:

@model IEnumerable<SStore.WebUI.Models.NavLink>
@{
    Layout = null;
}

@foreach (var link in Model)
{
    Html.RouteLink(link.Text, link.RouteValues);
}

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 using Menu.ascx which 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM