title: Accessing Configuration Settings in Javascript using ASP.NET Core 2 MVC
body: <p>I'm currently building a simple website using ASP.NET Core 2 and bootstrap. The site will be deployed to a staging and production environment so I want to be able to configure some settings using Configuration Key/Value pairs I can set in Azure. I also want these values to be available to me in Javascript.</p>
  
  <p>Thanks to this <a href="http://benjii.me/2016/04/new-configuration-appsettings-mvc6-web-config-gone/" rel="nofollow noreferrer">helpful blog post</a> I have worked out how to create an AppSettings class and populate it. This post also covers using dependency injection to access AppSettings from a RazorPage model.</p>
  
  <p><strong>My appsettings.json file</strong></p>
  
  <pre><code>{
      "AppSettings": {
          "TestProperty": "Test_Property"
      },
      "Logging": {
          "IncludeScopes": false,
          "LogLevel": {
              "Default": "Warning"
          }
      }
  }
  </code></pre>
  
  <p><strong>Automatically bind my AppSettings class in Startup.cs</strong></p>
  
  <pre><code>services.Configure&lt;AppSettings&gt;(Configuration.GetSection(nameOf(AppSettings)));
  </code></pre>
  
  <p><strong>Accessing the settings via dependency injection:</strong></p>
  
  <pre><code>public class HomeModel : PageModel
  {
      private readonly AppSettings _appSettings;
  
      public string TestProperty {get; set;}
  
      public HomeModel(IOptions&lt;AppSettings&gt; appSettings)
      {
          _appSettings = appSettings.Value;
      }
  
      public IActionResult Index()
      {
          TestProperty = _appSettings.TestProperty;
  
          return View();
      }
  }
  </code></pre>
  
  <p><strong>Then on the page where I want to use this property in javascript I do the following to create a javascript property with the setting:</strong></p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
    var testProperty = '@Model.TestProperty';
  &lt;/script&gt;
  </code></pre>
  
  <p>This works but ideally I don't want to have to configure every page to use this dependency injection and expose my <code>TestProperty</code> on every page. I would like to be able to put the above code in my <code>_Layout.cshtml</code> in which every page's body is rendered (or somewhere else appropriate) so I can create a javascript variable for use on every page.</p>
  
  <p>I have thought about using a BaseViewModel from which all my page's models are inherited but experimenting with this hasn't resulted in anything useful (just a exceptions).</p>
  
  <p><strong>How would you go about creating a javascript property from a configuration setting with the ability to configure only once?</strong></p>