Yon can use the @Html.RenderAction() function available in ASP.NET MVC to display this information.
_Layout.cshtml View
@{Html.RenderAction("UserInfo", "Account");}
Show model
public class UserInfo { public bool IsAuthenticated {get;set;} public string ForeName {get;set;} }
Account controller
public PartialViewResult UserInfo() { var model = new UserInfo(); model.IsAutenticated = httpContext.User.Identity.IsAuthenticated; if(model.IsAuthenticated) {
View UserInfo
@model UserInfo @if(Model.IsAuthenticated) { <text>Hello, <strong>@Model.ForeName</strong>! [ @Html.ActionLink("Log Off", "LogOff", "Account") ] </text> } else { @:[ @Html.ActionLink("Log On", "LogOn", "Account") ] }
This does a few things and brings in some options:
- Keeps your opinion of the need to sniff HttpContext. Let the controller handle this.
- Now you can combine this with the [OutputCache] attribute, so you do not need to display it on every page.
- If you need to add more information to the UserInfo screen, it will be as simple as updating the ViewModel and populating the data. No magic, no ViewBag, etc.
source share