![](/img/trans.png)
[英]Pass ViewBag to PartialView from action controller that returns that PartialView
[英]How to pass value from Controller to _Layout and futher to PartialView without ViewBag?
所以我有下一個應用程序架構:
通常,請求轉到RenderBody部分中的ListController。
菜單具有搜索文本框。 當用戶想要搜索某些內容時,searchText會作為參數進入ListController。
我想在同一文本框中單擊“查找”后放置搜索文本。 我應該如何做才能使這個工作流程更加美觀?
我希望我的照片能帶來一些清晰度。 謝謝。
<!-- _Layout (approximate markup) -->
<html>
<head></head>
<body>
@Html.Action("MenuLeft", "Nav")
<div>
@RenderBody()
</div>
</body>
</html>
<!-- Menu PartialView -->
@using (Html.BeginForm("All", "List"))
{
@Html.TextBox("SearchText", null) // searchText should be here
<button type="submit"></button>
}
// Menu Controller
public class NavController : Controller
{
public PartialViewResult Menu()
{
return PartialView("MenuPartial");
}
}
public class ListController : Controller
{
public ViewResult All(String searchText = null)
{
...
return View(model);
}
}
使用視圖模型
_Layout
也可以接受模型,就像視圖和部分視圖一樣。
一種使用此方法的方法是創建一個基本ViewModel,該模型具有_Layout(或_Layout呈現的任何局部視圖)中所需的屬性,並從中派生所有其他視圖模型。
public class ViewModelBase {
public string SearchText {get;}
public ViewModelBase(string searchText) {
SearchText = searchText;
}
}
public class ListModel : ViewModelBase {
public ListModel( ..., searchText) : base(searchText) {
...
}
}
在_Layout中,設置模型類型,您將可以訪問ViewModeBase屬性,並在調用中傳遞searchText
值以呈現菜單。
<!-- _Layout (approximate markup) -->
@model ViewModelBase
<html>
<head></head>
<body>
@Html.Action("Menu", "Nav", Model.SearchText)
<div>
@RenderBody()
</div>
</body>
</html>
更新您的NavController以接受搜索文本值:
// Menu Controller
public class NavController : Controller
{
public PartialViewResult Menu(string searchText = null)
{
return PartialView("MenuPartial", searchText);
}
}
更新您的Menu PartialView以使用string
模型並設置搜索框的值:
<!-- Menu PartialView -->
@model string
@using (Html.BeginForm("All", "List"))
{
@Html.TextBox("SearchText", Model) // searchText should be here
<button type="submit"></button>
}
我建議您一旦完成此工作,就回頭給菜單PartialView提供自己的包含SearchText
屬性的視圖模型。
查看模型與ViewBag
視圖模型應優於ViewBag。 可以在這里找到完整的說明, ViewModels或ViewBag? ,但是好處的簡要概述是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.