如何在没有ViewBag的情况下将值从Controller传递到_Layout并进一步传递给PartialView?

时间:2019-01-06 15:36:45

标签: c# asp.net-mvc razor

所以我有下一个应用程序架构:

  1. NavController,ListController
  2. _Layout,由NavController和RenderBody部分中的Menu(= PartialViewResult)组成。

通常,请求转到RenderBody部分中的ListController。

菜单具有搜索文本框。当用户想要搜索某些内容时,searchText会作为参数进入ListController。

我想在同一文本框中单击“查找”后放置搜索文本。我应该如何做才能使工作流程更加美观?

我希望我的照片能带来一些清晰度。谢谢。

appArchitecture

<!-- _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);
    }
}

1 个答案:

答案 0 :(得分:0)

使用视图模型

_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 or ViewBag?处找到完整的说明,但好处的简要说明如下:

  • 编译时间检查
  • 自信重构的能力
  • IDE支持-例如导航到所有用法的功能
  • 智能感知