In my ASP MVC 3 website, I need a way to determine user security on a shared layout page. This layout page houses a navbar that needs to display drop down items based on a user's security level.
Originally I had thought I could make an Ajax call and populate a ViewBag item, then use that to determine what to show/not show. However, this won't work unless I want to put that same method in every controller/method.
Given this set up (navbar located on a shared layout), what is the best method for determining which items to show as the user navigates across different controllers/methods?
You could go two ways about this.
You could do a check in the View:
@if (User.Identity.IsAuthenticated){ // show logged in view } else{ // show logged out view }Or you could build a ViewModel and populate that from a shared action.
Example:
ViewModel public class VM { public string Text{get; set;} } Shared Action on Shared Controller: public class SharedController{ public PartialViewResult GetMenu(){ VM newvm = new VM(Text = "not logged in"); if (User.Identity.IsAuthenticated){ newvm.Text = "logged in"; } return PartialView("Shared", newvm); } } A partialview to render this action: @Model VM <p> @model.Text </p> And lastly in your view:@{ Html.RenderAction("Shared", "Shared"); }