18

In MVC2 I have used Page.User.Identity.Name using the <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

How can I use the same in MVC3?

3 Answers 3

29

You can always do something like:

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

but don't.

Normally a view shouldn't try to fetch such information. It is there to display whatever information is passed by the controller. It should be strongly typed to a model class which is passed by a controller action.

So in the controller action rendering this view:

[Authorize]
public ActionResult Index()
{
    var model = new MyViewModel
    {
        Username = User.Identity.Name
    }
    return View(model);
}

Now inside the view feel free to use this information:

@Model.Username
Sign up to request clarification or add additional context in comments.

8 Comments

I have not understood, im using FormsAuthentication.RedirectFromLoginPage(user.Name, model.RememberMe); and in another view im trying to load the user name using in _LogOnPartial.cshtml using @if(Request.IsAuthenticated) { <text>Welcome <b>@Page.User.Identity.Name</b>! [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text> } else { @:[ @Html.ActionLink("Log On", "LogOn", "Account") ] }
Whats the use of _LogOnPartial.cshtml in that case? and I just cant do that for all the views?
@user281180, you shouldn't use FormsAuthentication.RedirectFromLoginPage in an ASP.NET MVC application. The correct way of performing a redirect is to return RedirectToAction("LoggedIn", "SomeController") after having set the authentication cookie to the response (using FormsAuthentication.SetAuthCookie). Then inside the LoggedIn action simply fetch the username and pass it to the view model. So use @Model.Username instead of @Page.User.Identity.Name.
Of course if you don't want to use strongly typed views you can always use @Html.ViewContext.HttpContext.User.Identity.Name.
SetAuthCookie is absolutely identical to RedirectFromLoginPage except that it doesn't perform the redirect because as I explained redirects in ASP.NET MVC should be performed by a controller action returning a RedirectToAction result.
|
11

MVC 2

<%: this.Page.User.Identity.Name %>

MVC 3

@this.User.Identity.Name

Comments

1

I had the same problem. I used this tutorial to solve this issue.

In short, in your view, put this code:

@Context.User.Identity.Name

Just make sure that the project is set to authenticate with windows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.