我正在使用新项目模板中的 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") ]
}
这会做一些事情并带来一些选项
- 使您的 View 不必嗅探 HttpContext。让 Controller 来处理这个问题。
- 您现在可以将其与 [OutputCache] 属性结合使用,这样您就不必每次都渲染它。单例的。页码。
- 如果您需要向“帐户信息”屏幕添加更多内容,只需更新 ViewModel 并填充数据即可。没有魔法,没有 ViewBag 等。
关于asp.net - 在 _LogonPartial 中显示模型数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12252343/