在_LogonPartial中显示模型数据

Chr*_*isO 2 asp.net asp.net-mvc-3

我正在使用新项目模板中的ASP MVC3,它给了我_Layout.cshtml和_LogOnPartial.cshtml.在_LogOnPartial中,有一个用户登录时显示的文本.如何在我的模型中显示我自己的附加数据并在所有视图中显示?

这是我尝试过的,但当然它没有用,因为没有模型数据:

@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") ]
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*mmy 5

我们有类似的东西,并使用Html.RenderAction()来实际显示帐户信息框.基本上,这将是一个非常简单的设置

布局视图

@{Html.RenderAction("Information", "Account");}
Run Code Online (Sandbox Code Playgroud)

视图模型

public class AccountInformation(){
    public bool IsAuthenticated {get;set;}
    public string UserName {get;set;}
    public int AccountBalance {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

账户管理员

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);
}
Run Code Online (Sandbox Code Playgroud)

信息查看

@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") ]
}
Run Code Online (Sandbox Code Playgroud)

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

  1. 保持您的视图不必嗅探HttpContext.让控制器处理.
  2. 您现在可以将它与[OutputCache]属性结合使用,这样您就不必每次都渲染它.单.页.
  3. 如果您需要在"帐户信息"屏幕中添加更多内容,则只需更新ViewModel并填充数据即可.没有魔法,没有ViewBag等.