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?
The User property provides programmatic access to the properties and methods of the IPrincipal interface. Because ASP.NET pages contain a default reference to the System. Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .
to get the current user name, however if you want to see all users record then you need to get the username by using its id, you can do this operation by joining Users table on user.id key or you can use it in View by having a method that take user id as parameter and return its Name.
cs change the property Email to UserName , remove the [EmailAddress] annotation from there and change the [Display(Name = "Email")] to [Display(Name = "Login")] or something you want to display. If you want to keep Email property, then add UserName property to the same view model and make it as required.
Windows Authentication is used in conjunction with IIS authentication. The Authentication is performed by IIS in one of three ways such as basic, digest, or Integrated Windows Authentication. When IIS authentication is completed, then ASP.NET uses the authenticated identity to authorize access.
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
MVC 2
<%: this.Page.User.Identity.Name %>
MVC 3
@this.User.Identity.Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With