使用SimpleMembership获取用户信息 [英] Getting User Information using SimpleMembership

查看:110
本文介绍了使用SimpleMembership获取用户信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍然试图通过MVC4掌握新的SimpleMembership.我更改了模型,使其包括可以正常工作的姓氏和姓氏.

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

我想更改登录时显示的信息,而不是在视图中使用User.Identity.Name,我想要做类似User.Identity.Forename的操作,什么是最好的方法?

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?

推荐答案

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

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

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

这可以做一些事情,并提供一些选项:

This does a few things and brings in some options:

  1. 使您的视图不必嗅探HttpContext.让控制器来处理这个问题.
  2. 您现在可以将其与 [OutputCache] 属性,因此您不必在每个页面中都呈现它.
  3. 如果需要在UserInfo屏幕上添加更多内容,就像更新ViewModel和填充数据一样简单.没有魔术,没有ViewBag,等等.
  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.

这篇关于使用SimpleMembership获取用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆