首页 文章

RazorView / RazorPages相关数据

提问于
浏览
-5

我有一些特定于每个剃刀视图的数据,我不想对每个视图进行硬编码 . 所以,我想在每个视图中添加与视图相关的编译时数据 .

  • 自定义属性对我不起作用,因为我们无法向剃刀视图添加自定义属性 .

  • 我不想为每个请求或到达视图时从数据源(字典等)重新获取/填充此数据 .

那么,有没有办法在asp.net应用程序的整个生命周期中同时将数据附加到每个视图?

Note 其实我想静态地为每个视图添加webpack生成的脚本/样式 . 它们的链接包括哈希值,因此它们会在源脚本/样式发生变化所以,我只想通过asp.net应用程序将它们添加到每个视图中一次(相当于在视图中键入它们),而不是每次加载视图时 .

3 回答

  • -1

    我创建了一个demo application for you here .

    您将需要使用appsettings.json文件,并将您的设置注入视图 .

    在我的appsettings.json中,我添加了一个名为"ViewConfiguration"的部分:

    "ViewConfiguration": {
        "ExampleKey": "ExampleValue"
    }
    

    您的各种值将需要进入ViewConfiguration部分 .

    例如,我有 ExampleKey ,您将使用通用名称,如"IndexPageStyleSheet",并且我有 ExampleValue ,您将需要使用新的样式表路径更新每个版本 . 这只需要在文件名更改时更新 .

    然后我创建了一个ViewConfiguration class,它存储了appsettings.json文件中的所有值 .

    您需要为每个配置行创建一个属性,并确保该属性的名称与appsettings.json中的键名相匹配 .

    例如,我的appsettings.json有 ExampleKey ,我的ViewConfiguration类也有一个 ExampleKey .

    public class ViewConfiguration {
        public string ExampleKey { get; set; }
    }
    

    在Startup.cs中,您需要告诉IOC容器将配置值加载到配置对象中 .

    my Startup.cs中,我的 ConfigureServices 方法会自动将"ExampleValue"加载到ViewConfiguration.ExampleKey中 .

    public void ConfigureServices(IServiceCollection services) {
            // This line is the magic that loads the values from appsettings.json into a ViewConfiguration object.
            services.Configure<ViewConfiguration>(Configuration.GetSection("ViewConfiguration"));
    
            services.AddMvc();
        }
    

    现在,在我的_ViewImports.cshtml中,我注入了我的ViewConfiguration对象,这样我就不需要将它注入每一页 . 这可以是 _ViewImports.cshtml 文件中的任何位置 . 如果您只想为每个文件夹注入特定配置,则可以为每个文件夹创建一个新的_ViewImports.cshtml文件,并为每个文件夹注入不同的配置对象 . 它很灵活 .

    @using Microsoft.Extensions.Options;
    
    @* Please rename this variable to something more appropriate to your application: *@
    @inject IOptions<ViewConfiguration> InjectedViewConfig
    

    现在,在任何页面中,您只需引用 ViewConfiguration 对象中的属性即可 .

    例如,在my Index.cshtml中,我通过引用 InjectedViewConfig.Value 上的强类型属性来引用 ViewConfiguration.ExampleKey 属性,并在页面上输出"ExampleValue" .

    这个值可以很容易地作为文件名注入到脚本或css链接标记中 . 它非常灵活 .

    <h1>Value: @InjectedViewConfig.Value.ExampleKey</h1>
    

    Example output

    通过进一步研究,您将能够从任何配置源(例如Azure应用程序设置或Azure Key Vault)注入这些值 . 有关详细信息,请参阅this article .

  • 2

    如果您使用的是mvc,则可以创建模型并将其添加到视图中 . 由于您不想为每个视图重新创建,因此可以创建只读变量 .

    static readonly MyModel ModelData = new MyModel { PropName = "Hello" };
    public IActionResult Index () => View(ModelData);
    

    在您的视图中,您现在可以强烈键入值 . 如果您要使用MVVM,可以参考ViewModel concept still exists in ASP.NET MVC Core?

  • 0

    实现IFileProvider和IFileInfo可以在编译时更改视图的内容 . 因此,我们可以用模板引擎(即http://dotliquidmarkup.org/)替换和提供视图中的静态数据 .

    检查一下; https://www.mikesdotnetting.com/article/301/loading-asp-net-core-mvc-views-from-a-database-or-other-location

相关问题