asp.net - 在 _LogonPartial 中显示模型数据

标签 asp.net asp.net-mvc-3

我正在使用新项目模板中的 ASP MVC3,该模板为我提供了 _Layout.cshtml 和 _LogOnPartial.cshtml。在 _LogOnPartial 中,有用户登录时显示的文本。如何在模型中显示我自己的附加数据并使其在所有 View 中显示?

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

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

最佳答案

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

布局 View

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

View 模型

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

帐户 Controller

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. 使您的 View 不必嗅探 HttpContext。让 Controller 来处理这个问题。
  2. 您现在可以将其与 [OutputCache] 属性结合使用,这样您就不必每次都渲染它。单例的。页码。
  3. 如果您需要向“帐户信息”屏幕添加更多内容,只需更新 ViewModel 并填充数据即可。没有魔法,没有 ViewBag 等。

关于asp.net - 在 _LogonPartial 中显示模型数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12252343/

相关文章:

c# - Ajax.ActionLink 从一个 View 发布整个模型?

c# - ASP.NET Web API - 驼峰式 XML

asp.net - C# ASP.NET - 无法通过 GridView 更新数据

c# - 用于开发和生产的 .NET Core API 条件身份验证属性

c# - asp.net mvc c#中的Json序列化

asp.net-mvc-3 - 为什么选择 MVC 3 的 ioc 框架?

c# - Html.DropDownList 从列表中选择值<string>

asp.net - 如何从C#代码中调用网址

c# - ExecuteNonQuery 不起作用

c# - 异步 Controller (MVC),具有 "stops"的长时间运行进程