Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to inject configuration settings into Javascript in an MVC app?

What is the best way to inject configuration settings into Javascript in an MVC app? I've seen how it is done using ASP.NET webforms, but not sure how to do this with MVC.

@using System.Configuration
...

var checkTimer = @ConfigurationManager.AppSettings["CheckTimer"];

In Web.config:

<appSettings>        
    <!-- Polling timer to check for alerts -->
    <add key="CheckTimer" value="10000"/>    
</appSettings>

But in my rendered output I just get the following:

var checkTimer = ;
like image 780
jaffa Avatar asked May 20 '11 10:05

jaffa


People also ask

Where do I put JavaScript code in MVC?

The recommended approach is to put in a separate JavaScript file or inside a section defined in Layout page. A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under <head> tag for scripts like below.

Can we use JavaScript in ASP NET MVC?

JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.

Can JavaScript read web config?

<add key="serverip" value="###. ##. #. ##"/>

What is configuration in MVC?

ASP.NET MVC configuration In ASP.NET apps, configuration uses the built-in . NET configuration files, web. config in the app folder and machine. config on the server. Most ASP.NET MVC and Web API apps store their settings in the configuration file's appSettings or connectionStrings elements.


1 Answers

var checkTimer = @Html.Raw(Json.Encode(ConfigurationManager.AppSettings["CheckTimer"]));
like image 143
Darin Dimitrov Avatar answered Oct 11 '22 09:10

Darin Dimitrov