I have settings in AppSettings (web.config) and I need to pass them to an external javascript file.
In ASP.NET I would think of an ASHX handler to write the javascript file to the response replacing placeholders with the settings values.
Is there a better way to do it in ASP.NET MVC? Thank you.
You could send them via a
JsonResult?In your JS, you’d have a request which sends a
GET/POSTrequest to a particular action (let’s call itGetAppSetting(), and the corresponding value is returned in the response.For security reasons, I would restrict what can be requested though…
Alternatively, it has been suggested by Chris Marisic in the comments that you may want to absolutely limit this to just a specific set of key/values for developer reasons. Therefore, here is a quick example of that…
Note the
JsonRequestBehavior.AllowGetin the JsonResults (MVC 2 only). This is because, by default, ASP.NET MVC 2 will not allowGETrequests on actions which return a JsonResult. You can circumvent this by adding the JsonRequestBehaviour, but I should probably mention that you should consider doing a post request in order to retrieve this information, and remove this behaviour in your action.