Retrieving User Information Using SimpleMembership

Still trying to handle the new SimpleMembership with MVC4. I changed the model to include a first and last name that work great.

I want to change the information displayed when I log in, instead of using User.Identity.Name in the view. I want to do something like User.Identity.Forename, what is the best way to accomplish this?

+4
source share
1 answer

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) { // Hit the database and retrieve the Forename model.ForeName = Database.Users.Single(u => u.UserName == httpContext.User.Identity.UserName).ForeName; //Return populated ViewModel return this.PartialView(model); } //return the model with IsAuthenticated only return this.PartialView(model); } 

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.
+5
source

Source: https://habr.com/ru/post/1436008/


All Articles