(十三)在ASP.NET CORE中使用Options

  • 这一节介绍Options方法,继续在OptionsBindSample项目下。
  • 在项目中添加一个Controllers文件夹,文件夹添加一个HomeController控制器
  • HomeController.cs
  •  1         private readonly Class _myClass;
     2 
     3         public HomeController(IOptions<Class> classAccesser)//IOptions的方法注入
     4         {
     5             this._myClass = classAccesser.Value;
     6         } 
     7 
     8         public IActionResult Index()
     9         {
    10             return View(_myClass);
    11         }

     

  • 在项目中添加一个Views文件夹,文件夹中添加一个Home文件夹(这和ASP.NET MVC一样),Home文件夹下添加一个Index.cshtml
  •  1 @model OptionsBindSample.Class
     2  3 @{
     4     ViewData["Title"] = "Index";
     5 }
     6 
     7 <h2>Index</h2>
     8 
     9 <div>
    10     @foreach(var stu in Model.Students)
    11     {
    12         <span>Name:@stu.Name</span>
    13         <span>Age:@stu.Age</span>
    14 
    15     }
    16 </div>

     

  • 此时StartUp.cs应该改成这样
  •  1         public IConfiguration Configuration { get; set; }
     2 
     3         public Startup(IConfiguration configuration)
     4         {
     5             this.Configuration = configuration;
     6         }
     7 
     8         // This method gets called by the runtime. Use this method to add services to the container.
     9         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    10         public void ConfigureServices(IServiceCollection services)
    11         {
    12             services.Configure<Class>(Configuration);
    13 
    14             services.AddMvc();
    15         }
    16 
    17         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    18         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    19         {
    20             if (env.IsDevelopment())
    21             {
    22                 app.UseDeveloperExceptionPage();
    23             }
    24 
    25             app.UseMvcWithDefaultRoute();
    26         }

     

也可以不用在Controller中依赖注入,而在视图中注入,改成如下:

HomeController.cs

1         public IActionResult Index()
2         {
3 return View(); 4 }

Index.cshtml:

 1 @using Microsoft.Extensions.Options
 2 @inject IOptions<OptionsBindSample.Class> ClassAccesser
 3 @{
 4     ViewData["Title"] = "Index";
 5 }
 6 <h2>Index</h2>
 7 
 8 <div>
 9     @foreach(var stu in ClassAccesser.Value.Students)
10     {
11         <span>Name:@stu.Name</span>
12         <span>Age:@stu.Age</span>
13 
14     }
15 </div>

 

转载于:https://www.cnblogs.com/dotnetHui/p/9058235.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值