我是ASP.NET MVC的新手。希望将公共数据传递给应用程序中的所有页面。以下Pass data to layout that are common to all pages。仍然无法获取布局和控制器中的值。在视图和控制器之间传递公共数据
当用户登录到系统时,我将标志'UserhasLoggedIn'并重定向到另一个控制器操作。在布局中,如果标志设置为false,则添加检查,则不应显示菜单项并显示LoginPage。当页面被重定向到Home索引时,它不会得到'UserhasLoggedIn'标志。
Layout.cshtml:
@using WebApplication2.Models
@model ViewModelBase
<div class="btn-toolbar" style="background-color:dimgrey; padding-left:35px;padding-top:-10px;">
@if (null != Model && (bool)Model.IsuserLoggedIn)
{
foreach (var menuItem in Model.MenuItems)
{
<div class="btn-group">
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">menuItem.MenuName <span class="caret"></span></button>
<ul class="dropdown-menu">
@foreach (var subMenu in menuItem.SubMenu)
{
<li>@Html.ActionLink((string)subMenu.MenuName, (string)subMenu.ActionName, (string)subMenu.ControllerName)</li>
}
</ul>
</div>
}
}
<div class="btn-group pull-right" style="padding-right:35px">
@if (null == Model || !(bool)Model.IsuserLoggedIn)
{
<button class="btn btn-primary" onclick="location.href='@Url.Action("Login", "Account")'">Log in</button>
}
else
{
<button class="btn btn-primary" onclick="location.href='@Url.Action("LogOff", "Account")'">Log out </button>
}
</div>
</div>
我已经创建了可用于公共视图模型。
public abstract class ViewModelBase
{
public bool IsuserLoggedIn;
}
LoginViewModel:
public class LoginViewModel : ViewModelBase
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
HomeViewModel:
public class HomeViewModel : ViewModelBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
的AccountController登录操作:
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
return RedirectToAction("Index", "Home", new HomeViewModel() { IsuserLoggedIn = true, MenuItems=null });
}
HomeController中Index操作:不能够得到IsUserLoggedIn为true的nd甚至不在布局中。
public ActionResult Index(HomeViewModel baseModel)
{
baseModel.FirstName = "First";
baseModel.LastName = "Last Name";
return View(baseModel);
}
最初当页面加载值为false时。但是,当登录成功将帐户控制器的登录操作中的值设置为True时。设置为true后,为什么它没有反映在模型和布局中 – user2323308
你甚至读过答案吗? 'Index'方法中'IsuserLoggedIn'的值是'false',因为'DefaultModelBinder'不能** SET ** –
我需要在Index方法中显式地将值设置为true吗? – user2323308