Asp.net MVC剃刀 - 将数据发送到主要布局 [英] Asp.net mvc razor - Send data to main layout

查看:63
本文介绍了Asp.net MVC剃刀 - 将数据发送到主要布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在asp.net mvc的新手。
我创建一个asp.net mvc4空的应用程序,并增加了实体模型它。
我有一个页面布局,我想显示菜单分类,页眉,页脚vb.But我怎么能发送数据包含多一个实体对象(最新帖子,分类,标签)到页面布局?
谢谢

I am newbie in asp.net mvc. I created an asp.net mvc4 empty application and added an entity model to it. I have a layout page which I want to display menu categories,header,footer vb.But how can I send the data contains one more entity object(last posts,categories,tags) to layout page ? Thanks

推荐答案

如果你要传递的数据(来自数据库来我假设),你所面临的,你必须传递给每一页数据的场景中的布局视图你的申请。因此,我会做的是建立一个基本的控制器从所有的控制器将继承:

If you want to pass data (coming from database I assume) to the layout view you are facing a scenario where you have data that is passed to every page in your application. So what I would do is create a base controller from which all your controllers will inherit:

public class BaseController : Controller
{
   public LayoutModel model;

   public BaseController()
   {
       // Here you will use some business logic to populate your Layout Model
       // You might also consider placing this model into the cache to prevent constant fetching of data from the database on each page request.
       model = _service.Populate();
       ViewBag.LayoutModel = model;
   }
}

正如你可以看到我使用的基本控制器的构造函数来获取所需的布局视图中的数据。我做了一个属性命名模型,并使用了一些所谓的填充业务逻辑方法(你需要写自己)来填充模型变量。然后,我的模型放入ViewBag。

As you can see I used the constructor of the base controller to fetch the data needed for your layout view. I made a property named model and used some business logic method called Populate (you need to write this yourself) to populate the model variable. Then I place the model into the ViewBag.

一旦我有这样的设置,然后每个控制器我做我的解决方案需要从基本控制器继承:

Once I have this set up then every controller I make in my solution needs to inherit from the base controller:

public class HomeController : BaseController
{
   // Controller code here...
}

这意味着每个控制器现在可以从主控制器访问模型的属性。

which means that every controller can now access the model property from the base controller.

在这里,您可以使用ViewBag.LayoutModel像这样每个视图(在视图顶部声明一个局部变量,并将其抛入基本类型):

From here you can use the ViewBag.LayoutModel on each view like this (declare a local variable at the top of the view and cast it into the underlying type):

@{
   LayoutModel MenuModel = ViewBag.LayoutModel;
}

,然后用它是这样的:

and then use it like this:

@MenuModel.SomeProperty

这仅仅是做到这一点的方法之一,但还有其他不太/更复杂的方式。你需要做一些自己的研究,看看哪种技术最适合您的...

This is just one of the ways to do it but there are other less/more complex ways. You need to do some research on your own and see which technique fits you the best...

这篇关于Asp.net MVC剃刀 - 将数据发送到主要布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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