• 任务13:在Core Mvc中使用Options


    13

    新建Controllers文件夹,在里面添加HomeController控制器

    新建Views文件夹,再新建Home文件夹。再新建Index.cshtml的视图页面

    注释上节课的代码,否则我们的管道都会被抵消,最后只输出了。appsettings.json文件的内容

    注入MVC

    添加默认路由,

    这样就把整个MVC的middleware添加到我们的应用程序当中

    使用IOptions是一个泛型的方法,把我们的Class传进去,

    Controller内输出代码

    @model OptionsBindSample.Class
    @{
        ViewData["Title"] = "Index";
    }
    <h2>Index</h2>
    <h4>Class No: @Model.ClassNo</h4>
    <h4>Class Desc: @Model.ClassDesc</h4>
    <h3>
        Students:
    </h3>
    <div>
        @foreach (var student in Model.Students)
        {
            <span>Name: @student.Name</span>
            <span>Age: @student.Age</span>
        }
    </div>
    Index.cshtml

    依赖注入和视图都完成后,要在Startup里面注册一下MyClass.把Configuration传进去。那么Options就会从这里读取到我们的IOptions那个方法里面去

    services.Configure<Class>(Configuration);

    运行页面,我们的options成功读取到了信息。

    在Controller里面进行依赖注入,显得代码有点单纯 多余,

    我们可以在视图中把这个配置中从依赖注入中直接读取出来。

    controller里面就是默认的返回

    直接在视图中注入

    @using Microsoft.Extensions.Options;
    @inject IOptions<OptionsBindSample.Class> ClassAccesser
    

    @{ ViewData["Title"] = "Index"; } <h2>Index</h2> <h4>Class No: @ClassAccesser.Value.ClassNo</h4> <h4>Class Desc: @ClassAccesser.Value.ClassDesc</h4> <h3> Students: </h3> <div> @foreach (var student in ClassAccesser.Value.Students) { <span>Name: @student.Name</span> <span>Age: @student.Age</span> } </div>

    Index.cshtml

    同样拿到了我们的结果



    如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Tips on Hair and Final gathering
    数学公式和符号的念法
    How to use Intel C++ Compiler in Visual Studio 2008
    Number Prefixes in Mathematics
    Glossy reflections/refractions in large scene
    atomic flushing data
    elvish Template Library Plan
    [Maxim07]中光线与三角形求交算法的推导
    C# 关闭窗体立即停止进程
    MS SQL 索引设计的准则
  • 原文地址:https://www.cnblogs.com/owenzh/p/11304075.html
Copyright © 2020-2023  润新知