I give data to the ViewBag in the IAuthorizationFilter.OnAuthorization process, and it puts for the _Layout.cshtml-in, but when I use a partial view in normal view the data in the ViewBag is null. This is normal behavior, or I am doing something wrong?
public class MyAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
filterContext.Controller.ViewBag.Name = this.name;
filterContext.Controller.ViewBag.Menus = user.GetMenu(this.role);
}
...
}
The _Layout.cshtml:
<section id="login">
Hello, <span class="username">@ViewBag.Name</span>!
</section>
<nav>
@Html.MenuLink(ViewBag.Menus as List<Entity.Models.MENU>, (string)ViewBag.Name)
</nav>
The view:
@model Web.ViewModels.RegistrationEntryViewModel
@Html.Partial("_RegistrationEntry", Model)
The action:
[MyAuthorize("ADMINISTRATORS")]
[HttpGet]
public ActionResult NewRegistrationEntry()
{
//The viewbag is already null here
...
}
Please stop using ViewBag
like that. It is not designed for this. And reason ViewBag
is null in controller (I suspect) that these are different ViewBag
objects in filter and in controller.
If you need to do repetitive actions in your view, there are better ways to do that. For your menu I would create an action that reads menu information, puts that in a ViewModel
(not in a ViewBag
) and outputs a partial view. Then in your Layout I'd render that partial action. (Also add some caching on this partial view)