如何在MVC视图页面中显示全名和电子邮件地址?我正在使用Windows身份验证登录。我的应用程序没有任何用户模块。我需要一个吗?我不想显示用户的ID示例:
<p>@User.Identity.Name</p>
答案 0 :(得分:0)
第1步:向ApplicationUser类中的IdentityModel添加两个新属性:[FirstName]和[LastName]
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public async Task<ClaimsIdentity> .........
}
步骤2:在RegisterViewModel类中,添加以下属性,
[Required]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
第3步:在“注册”视图中,获取[名字]和[姓氏]
步骤4:更新帐户控制器中的POST方法,如下所示,
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName
};
...........
...........
}
第5步:运行迁移以更新数据库以使故事中包含[FirstName]和[LastName]
第6步:创建如下基本控制器类,
public class ApplicationBaseController : Controller
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (User != null)
{
var context = new ApplicationDbContext();
var username = User.Identity.Name;
if (!string.IsNullOrEmpty(username))
{
var user = context.Users.SingleOrDefault(u => u.UserName == username);
string fullName = string.Concat(new string[] { user.FirstName, " ", user.LastName });
ViewData.Add("FullName", fullName);
}
}
base.OnActionExecuted(filterContext);
}
public ApplicationBaseController()
{ }
}
第7步:将ApplicationBaseController添加为HomeController的基类
public class HomeController : ApplicationBaseController
步骤8:将_LoginPartial.cshtml更改为显示[FullName]
ViewData["FullName"]
希望这会有所帮助。