首页 > 解决方案 > 端口布局视图模型到 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>

标签: c#asp.netasp.net-mvcasp.net-core

解决方案


在 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>

推荐阅读