将数据传递给所有页面通用的布局 [英] Pass data to layout that are common to all pages

查看:27
本文介绍了将数据传递给所有页面通用的布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有布局页面的网站.然而,这个布局页面有数据,所有页面模型都必须提供这样的页面标题、页面名称和我们实际所在的位置,用于执行某些操作的 HTML 帮助程序.此外,每个页面都有自己的视图模型属性.

我该怎么做?输入布局似乎是个坏主意,但我如何传递这些信息?

解决方案

如果您需要将相同的属性传递给每个页面,那么创建一个所有视图模型都使用的基本视图模型将是明智之举.然后,您的布局页面可以采用此基本模型.

如果此数据背后需要逻辑,则应将其放入所有控制器使用的基本控制器中.

您可以做很多事情,重要的方法是不要在多个地方重复相同的代码.

从下面的评论更新

这是一个简单的例子来演示这个概念.

创建一个所有视图模型都将继承的基础视图模型.

公共抽象类 ViewModelBase{公共字符串名称 { 获取;放;}}公共类 HomeViewModel : ViewModelBase{}

您的布局页面可以以此为模型.

@model ViewModelBase<!DOCTYPE html><头><meta name="viewport" content="width=device-width"/><title>测试</title><身体><标题>你好@Model.Name</标题><div>@this.RenderBody()

最后在action方法中设置数据.

公共类 HomeController{公共 ActionResult 索引(){返回 this.View(new HomeViewModel { Name = "Bacon" });}}

I have a website which have a layout page. However this layout page have data which all pages model must provide such page title, page name and the location where we actually are for an HTML helper I did which perform some action. Also each page have their own view models properties.

How can I do this? It seems that its a bad idea to type a layout but how do I pass theses infos?

解决方案

If you are required to pass the same properties to each page, then creating a base viewmodel that is used by all your view models would be wise. Your layout page can then take this base model.

If there is logic required behind this data, then this should be put into a base controller that is used by all your controllers.

There are a lot of things you could do, the important approach being not to repeat the same code in multiple places.

Edit: Update from comments below

Here is a simple example to demonstrate the concept.

Create a base view model that all view models will inherit from.

public abstract class ViewModelBase
{
    public string Name { get; set; }
}

public class HomeViewModel : ViewModelBase
{
}

Your layout page can take this as it's model.

@model ViewModelBase
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Test</title>
    </head>
    <body>
        <header>
            Hello @Model.Name
        </header>
        <div>
            @this.RenderBody()
        </div>
    </body>
</html>

Finally set the data in the action method.

public class HomeController
{
    public ActionResult Index()
    {
        return this.View(new HomeViewModel { Name = "Bacon" });
    }
}

这篇关于将数据传递给所有页面通用的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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