Alex Rivera | Logout

How to expose global object like @User in razor views?

Asked 2011-12-20T17:45:48.903
16

How/Where can I declare an object like @User so that it can be referenced globally in any razor view using @?

Something similar to:

_LoginPartial.cshtml:

@if(Request.IsAuthenticated) {
    <text>Signed In As  <strong>@User.Identity.Name</strong> |

but instead reference my object:

  @if(this && that) { <text>@MyObject.GetData</text> }
Edit
Report

1 Answer

2

You could probably do something like this in your View:

@Html.ViewContext.HttpContext.User.Identity.Name

I would recommend against that however, and add this information to a ViewModel. For example:

public ActionResult SomeController()
{
    var model = new MyViewModel
    {
        Username = User.Identity.Name
    }
    return View(model);
}

Now inside the view you can display this information:

@Model.Username
answered 2011-12-20T17:54:50.853

Your Answer