c# - 端口布局视图模型到 Asp.Net Core
问题描述
我将 ASP.NET 电子商务应用程序移植到 ASP Net Core。在我的应用程序中,我使用的是 LayoutViewModel 并将其填充到基本控制器中(例如类别,因为所有视图都需要类别)所以我可以在 _Layout.cshtml 中使用它。我如何将此结构移植到 ASP.NET Core 或者您有什么建议?我使用中间件还是?
谢谢你。
public class BaseController : Controller
{
protected override IAsyncResult BeginExecute(HttpContext requestContext,
AsyncCallback callback,
object state)
{
...
var layoutViewModel = new LayoutViewModel
{
Categories = Categories,
};
ViewBag.LayoutViewModel = layoutViewModel;
...
}
}
public class HomeController:BaseController
{
public ActionResult Index()
{
var myHomeViewModel= new MyHomeViewModel{Prop="Test"};
return View(myHomeViewModel);
}
}
//In _Layout.cshtml
@{
var layoutViewModel = (LayoutViewModel)ViewBag.LayoutViewModel
}
<div class="container">
<div class="header">
For Example Categories Count: @layoutViewModel.Categories.Count
</div>
<div class="body">
@RenderBody()
</div>
<div class="footer">
</div>
</div>
解决方案
在 ASP.Net Core 中,您可以使用View 组件来定义您的逻辑,以在 InvokeAsync 方法中获取数据,并将其呈现在您的局部视图中。
另一种选择是使用ActionFilter
. 例如,如果您有视图模型:
public class MainLayoutViewModel
{
public string PageTitle { get; set; }
}
创建ActionFilter
类:
public class CommonViewBagInitializerActionFilter : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
((Controller)context.Controller).ViewBag.MainLayoutViewModel = new MainLayoutViewModel() {
PageTitle = "MyTitle"
};
}
}
在函数中注册过滤器ConfigureServices
:
services.AddMvc(config =>
{
config.Filters.Add(new CommonViewBagInitializerActionFilter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
在你的_Layout.cshtml
:
@{
var viewModel = (MainLayoutViewModel)ViewBag.MainLayoutViewModel;
}
<title>@viewModel.PageTitle</title>
推荐阅读
- javascript - 从服务 Javascript 接收变量 - React Hooks
- python - Django:使用带有模型视图集的用户名查找用户 OnetoOne 字段(Django Rest API)
- github - Markdown 语法不适用于我的 GitHub 博客文章
- java - 我是Java新手,下面代码的逻辑是什么?
- eclipse - Eclipse + PyDev:使用文档字符串进行类型检查(如 PyCharm)
- java - 如何在 java 中创建一个可以包含 100 个地址簿条目的地址簿?
- java - 不在 Spring mvc Intellij 中渲染多个 JSP 页面
- java - 如何在树莓派上全屏运行 javafx 应用程序?
- android - 使用 OkHttp 进行真实 HTTP 请求的 Robolectric 测试抛出 java.lang.NullPointerException:没有为 PKCS#12 KeyStore 提供密码
- google-apps-script - 如何保护谷歌表格中的条件格式?