2012-09-03 41 views
2

我使用新的項目模板,它給了我_Layout.cshtml和_LogOnPartial.cshtml ASP MVC3。在_LogOnPartial中有用戶登錄時顯示的文本。如何在我的模型中顯示自己的附加數據並將其顯示在所有視圖中?在_Logon部分顯示模型數據

這裏就是我試過,但當然這是行不通的,因爲沒有模型數據:

@if(Request.IsAuthenticated) { 
<text>Hello, <strong>@User.Identity.Name</strong>! - Account Balance: @Model.GetAccountBalance() 
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text> 
} 
else { 
@:[ @Html.ActionLink("Log On", "LogOn", "Account") ] 
} 

回答

5

我們有類似的東西,並使用Html.RenderAction()來實際顯示帳戶信息框。基本上,這將是一個非常簡單的設置

佈局視圖

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

視圖模型

public class AccountInformation(){ 
    public bool IsAuthenticated {get;set;} 
    public string UserName {get;set;} 
    public int AccountBalance {get;set;} 
} 

賬戶控制器

public PartialViewResult Information(){ 
    var model = new AccountInformation(); 
    model.IsAutenticated = httpContext.User.Identity.IsAuthenticated; 
    if(model.IsAuthenticated){ 
     model.UserName = httpContext.User.Identity.Name; 
     model.AccountBalance = functionToGetAccountBalance(); 
     //Return the fully populated ViewModel 
     return this.PartialView(model); 
    } 
    //return the model with IsAuthenticated only set since none of the 
    //other properties are needed 
    return this.ParitalView(model); 
} 

信息查看

@model AccountInformation 

@if(Model.IsAuthenticated) { 
<text>Hello, <strong>@Model.UserName</strong>! - Account Balance: @Model.AccountBalance 
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text> 
} 
else { 
@:[ @Html.ActionLink("Log On", "LogOn", "Account") ] 
} 

這做了一些事情,在一些選項

  1. 保持不必嗅出周圍的HttpContext你的看法帶來的。讓控制者處理。
  2. 現在,您可以將其與[OutputCache]屬性結合使用,因此您無需將其呈現爲Every。單。頁。
  3. 如果您需要添加更多東西到帳戶信息屏幕,它就像更新ViewModel和填充數據一樣簡單。沒有魔法,沒有ViewBag等
+0

謝謝你的簡潔的答案。問題解決了! – ChrisO

-2

您必須修改視圖模型上使用此查看您的其他數據添加到它。