开发者

Rendering Navigation in MVC3

What's the best way to render Navigation in MVC3? In my app the Controller has to decide what should be in the开发者_StackOverflow Navigation but as far as I know there's no way to pass a Model up to the _Layout file (where the Navigation html lives) to give it this information.


You can make the model available to your layout.

  1. Define a base class, MyBaseModel, with the properties you want available to the layout.
  2. Have your models subclass MyBaseModel, and ensure that you populate the properties
  3. Have your layout specify @model MyBaseModel
  4. Use the properties

See also this blog post where a similar problem ("we often find ourselves needing to include the same information in every page") is tackled.


Best is a relative and subjective term. I would usually go with an approach similar to druttka's answer but another option is to use RenderAction() to invoke a controller action

<div>@Html.RenderAction("action", "controller")</div>


I will offer some counterpoints to @druttka's answer. But mostly, you have to decide which trade off you want to make.

If you use a model for your view, you are now forcing 2 things:

  1. Every view must be strongly typed
  2. Every action must call the function to populate all levels of nav included in your view model

The first point isn't so bad, because there are very few pages in a typical non-static site which wouldn't derive from a model anyway, and its easy enough to create an empty model for those pages. The second point is much more annoying however. Each function has to instantiate it's own model, and then populate the nav properties for every level of nav provided by the model. This can be quite cumbersome, but can be fairly elegantly handled in OnActionExecuted for at least nav which is not specific to a given action.

The alternative is to add the nav to the ViewBag. This can be done whenever and does not force you to specify a model for every view, which is great for the flexibility in those cases where you do not need to specify a model. It should be noted however that the ViewBag in asp.net mvc 3 is of type dynamic, which you cannot use as a parameter in a lambda function, thus preventing you from doing something like @Html.DisplayFor(viewBag => viewBag.MainNav) in your layout, which is a real drag. You can still render partial and specify the appropriate DisplayTemplate however.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜