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?
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
m 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") ] }s the use of _LogOnPartial.cshtml in that case? and I just cant do that for all the views?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.@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.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.