我試圖將我的UserModel傳遞給每個視圖,以便它可以顯示當前用戶信息。把模型放在每個視圖上
這是我BaseViewModel:
public class BaseViewModel
{
public UserModel currentUser { get; set; }
}
BaseController:
public class BaseController : Controller
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
UserRepository userRep = new UserRepository();
BaseViewModel model = new BaseViewModel
{
currentUser = userRep.getCurrentUser()
};
base.OnActionExecuted(filterContext);
}
}
的HomeController:(默認)
public class HomeController : BaseController
{
public ActionResult Index()
{
ListRepository listRep = new ListRepository();
return View(listRep.GetAllLists());//returns IEnumerable<ListModel>
}
}
我的共享_layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Public/css")
</head>
<body>
<header>
@Html.Partial("_Header")
</header>
@RenderBody()
</body>
</html>
最後,我_Header.cshtml:
<div id="logo">
<h1>Hello @Model.currentUser.username</ h1 >
</div>
但是當我運行它,我得到這個錯誤信息:
'System.Collections.Generic.List'不包含'currentUser'的定義
我想我的BaseViewModel
就會讓附加
我應該創建一個新的控制器還是將其添加到現有的控制器?另外,無關,是否有可能返回一個不同的局部視圖,取決於用戶是否登錄? – Cornwell
就個人而言,我會把它放在一個單獨的控制器(也許'UserController')中,假設你將在與多個控制器關聯的多個視圖中使用該部分 –
並且您可以隨時檢查請求是否已通過身份驗證,並使用'return PartialView(「abc 「,model);''''或'返回PartialView(」xyz「,model);'(甚至模型可能不同) –