加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用SimpleMembership获取用户信息

发布时间:2020-12-16 06:25:30 所属栏目:asp.Net 来源:网络整理
导读:仍在尝试用MVC4来掌握新的SimpleMembership.我改变了模型,包括Forename和Surname,它工作得很好. 我想更改登录时显示的信息,而不是在View中使用User.Identity.Name我想做像User.Identity.Forename这样的事情,最好的方法是什么? 解决方法 Yon可以利用ASP.NET
仍在尝试用MVC4来掌握新的SimpleMembership.我改变了模型,包括Forename和Surname,它工作得很好.

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

解决方法

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

_Layout.cshtml查看

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

查看模型

public class UserInfo
{
    public bool IsAuthenticated {get;set;}
    public string ForeName {get;set;}
}

账户管理员

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视图

@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") ]
}

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读