使用SimpleMembership获取用户信息

use*_*905 4 asp.net-mvc viewdata login user-data simplemembership

仍在尝试用MVC4来掌握新的SimpleMembership.我改变了模型,包括Forename和Surname,它工作得很好.

我想更改登录时显示的信息,而不是在View中使用User.Identity.Name我想做像User.Identity.Forename这样的事情,最好的方法是什么?

Len*_*rri 5

Yon可以利用@Html.RenderAction()ASP.NET MVC中提供的功能来显示这种信息.

_Layout.cshtml查看

@{Html.RenderAction("UserInfo", "Account");}
Run Code Online (Sandbox Code Playgroud)

查看模型

public class UserInfo
{
    public bool IsAuthenticated {get;set;}
    public string ForeName {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

账户管理员

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);
}
Run Code Online (Sandbox Code Playgroud)

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") ]
}
Run Code Online (Sandbox Code Playgroud)

这做了一些事情并带来了一些选择:

  1. 保持您的视图不必嗅探HttpContext.让控制器处理它.
  2. 您现在可以将它与[OutputCache]属性结合使用,这样您就不必在每个页面中呈现它.
  3. 如果您需要向UserInfo屏幕添加更多内容,则只需更新ViewModel并填充数据即可.没有魔法,没有ViewBag等.