Mvc:如何在_layout中协调部分视图的数据模型? [英] Mvc: how to coordinate the data model for a partial view in _layout?

查看:112
本文介绍了Mvc:如何在_layout中协调部分视图的数据模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个新闻侧边栏,应该通过所有其他视图保留在网站上,数据从数据库中提取到ViewBag中。



我应该如何构建网站以保留在所有页面中引用相同数据的部分视图(或部分...)?当其他站点视图依赖于不同的控制器时,模型/控制器和视图的分离阻碍了这种设计。



我尝试过:



我将此作为_layout调用的部分视图制作,并将其存储在Home控制器中查询并保存到ViewBag以供被调用的局部视图访问。



但是,当网站中的其他页面加载时,他们无权访问HomeController最初存储的数据模型。

I'm making a "News" sidebar that should persist on the website, through all other views, with data fetched from the database into the ViewBag.

How should I architect the site to persist a partial view (or section...) that references the same data across all pages? The separation of models/controllers and views stymies this design when other site views depend on different controllers.

What I have tried:

I crafted this as a partial view called by _layout and stocked it with data queried in the Home controller and saved to the ViewBag for access by the called partial view.

However, when other pages in the site load, they don't have access to the data model that was originally stocked by the HomeController.

推荐答案

我发现一个解决方案在架构上看起来比应用程序会话更灵活,并且由于数据可能会更改,因此会在重新加载表单时更新数据。



经过反思,我意识到我并不关心在会话中只获取一次数据(并且它可能在后台改变),而不是避免在每个控制器中重复编码获取。



因此,创建服务并使用依赖注入将其直接注入_Layout视图(或由其调用的局部视图)似乎是完美的解决方案。我永远不必触摸控制器在整个网站的侧面板中提供这些数据。



此链接提供了一个易于理解的示例:



将服务注入视图& mdash; ASP.NET文档
I found a solution that seems more flexible architecturally than app session, and since the data may change it will update the data when the forms are reloaded.

Upon reflection I realized that I'm not so much concerned about fetching the data only once in the session (and it may change in the background anyway), than with avoiding repetitive coding of the fetch in every controller.

So creating a service and using dependency injection to inject it directly into the _Layout view (or a partial view called by it) seems like the perfect solution. I never have to touch a controller to provide this data in a side panel throughout the website.

This link provides an easy-to follow example:

Injecting Services Into Views — ASP.NET documentation


这篇关于Mvc:如何在_layout中协调部分视图的数据模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆