我是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