Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to Inject IOptions<T> in _Layout

I built a small web app using ASP.NET Core Razor Pages, but I want to using IOptions<T> to pass settings from app.json in _Layout. Thanks!

like image 585
Ivan Ivanov Avatar asked Dec 28 '25 23:12

Ivan Ivanov


1 Answers

You can use the @inject Razor directive to inject services into your Razor views. Of course, that also includes options. So if you have some MyOptions class that you have configured (e.g. using services.Configure<MyOptions>(options => { … }) in the Startup class), then you can just inject the options into the .cshtml:

@inject IOptions<MyOptions> myOptions

<h1>@myOptions.Value.ApplicationTitle</h1>
<p>@myOptions.Value.ApplicationIntroText</p>

To avoid having to access myOptions.Value explicitly all the time, you can also use a code block and store the result in a local variable first:

@inject IOptions<MyOptions> myOptions
@{
    var opts = myOptions.Value;
}

<h1>@opts.ApplicationTitle</h1>
<p>@opts.ApplicationIntroText</p>
like image 144
poke Avatar answered Dec 30 '25 11:12

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!