Getting User Information using SimpleMembership

回眸只為那壹抹淺笑 提交于 2019-12-10 17:03:56

问题


Still trying to get to grips to the new SimpleMembership with MVC4. I changed the model to include Forename and Surname which works fine.

I want to change the information displayed when logged in so instead of using User.Identity.Name in the View I want to do something like User.Identity.Forename, what's the best way to accomplish this?


回答1:


Yon can leverage @Html.RenderAction() feature available in ASP.NET MVC to display this kind of info.

_Layout.cshtml View

@{Html.RenderAction("UserInfo", "Account");}

View 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);
}

UserInfo View

@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:

  1. Keeps your view from having to sniff around the HttpContext. Let's the controller deal with that.
  2. You can now combine this with an [OutputCache] attribute so you don't have to render it in every single page.
  3. If you need to add more stuff to the UserInfo screen, it is as simple as updating the ViewModel and populating the data. No magic, no ViewBag, etc.


来源:https://stackoverflow.com/questions/12572819/getting-user-information-using-simplemembership

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!