2012-09-24 67 views
4

仍在嘗試使用MVC4來處理新的SimpleMembership。我改變了模型,包括Forename和Surname,它工作正常。使用SimpleMembership獲取用戶信息

我想更改登錄時顯示的信息,而不是在視圖中使用User.Identity.Name我想要執行類似User.Identity.Forename的操作,那麼完成此操作的最佳方法是什麼?

回答

5

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

這做了幾件事情,並帶來了一些選項:

  1. 不必嗅出周圍的HttpContext保持您的看法。我們讓控制器處理。
  2. 現在,您可以將其與[OutputCache]屬性結合使用,因此您不必在每一頁中都進行渲染。
  3. 如果您需要添加更多內容到UserInfo屏幕,它就像更新ViewModel並填充數據一樣簡單。沒有魔法,沒有ViewBag等