How to read the web.config settings in the MVC controller method and access them in the form of angles, the controller and the service?

I need to read the appsettings web.config in the MVC controller method and pass them in to view and access the settings in the controller and angularjs service. I think that you need to do the application settings and prepare a dictionary with key / value pairs and pass it to the model object in my view. But how can I access them anywhere in an angular app?

+5
source share
2 answers

The way I do such things is pretty much the same as you suggest (using JSON.net and Razor):

  • I am preparing a dictionary or an object graph with the data that I want to make available.
  • Passing data as part of a ViewModel from a controller to a view
  • Serialize ViewModel data by entering it in the cshtml template as a global JavaScript variable. I have to use the following trick to get this working:
 <script> var AppSettings = (function(o) { return o; })(@Html.Raw(JsonConvert.SerializeObject(Model.AppSettings))); </script> 
  1. Create an angular service that reads (and copies) the global JavaScript variable.
  2. Data clients access it through the angular service.

A service is just a thin shell, although sometimes it contains logical and accessory methods. The value here is that you access a global variable (dirty practice in the angular world) from only one place in your code. "Encapsulate ugly things!"

Note. This requires your angular app to be sent from the MVC website using the cshtml template.

The advantage of this approach when creating an AJAX call is that the data of interest is available immediately after loading the angular application ... the data can be accessed through the service synchronously. This simplifies data access. If asynchrony is fine, I would suggest making an AJAX call from your service, cache the result, and return the promise. With the AJAX approach, there is no connection between the angular template and your MVC project, which allows you to serve your angular template as a simple html file.

+3
source

if you are not using asp.net mvc view, you can send ajax request to get server end configuration, server end configuration for this ajax request.

0
source

All Articles