我正在使用新项目模板中的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") ]
}
答案 0 :(得分: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 :(得分:-2)
您必须修改此视图中使用的ViewModel并将其他数据添加到其中。