Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read web.config settings in MVC controller method and access them in angularjs view, controller and service?

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

like image 280
Jyina Avatar asked Oct 20 '22 11:10

Jyina


1 Answers

The way I do this sort of thing is pretty much just as you suggest (using JSON.net and Razor):

  1. I prepare a dictionary or object graph with the data I want to make available.
  2. Pass data as part of the ViewModel from the controller to the view
  3. Serialize the ViewModel data, injecting it into the cshtml template as a global JavaScript variable. I have to use the following trick to get this to work:
<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. Clients of the data access it via the angular service.

The service is just a thin wrapper, though sometimes it contains logic and accessor methods. The value here is that you are only accessing the global variable (a 'dirty' practice in the angular world) from only one spot in your code. "Encapsulate the ugly stuff!"

Note: This does require that your angular app is served from the MVC website via a cshtml template.

The advantage of this approach over making an AJAX call is that the data of interest is available right when the angular app is bootstrapped... the data can be accessed via the service synchronously. This simplifies access to the data. If asynchrony is OK, I would suggest making an AJAX call from your service, caching the result, and returning a promise. With the AJAX approach there is no coupling between the angular template and your MVC project, allowing you to serve your angular template as a plain html file.

like image 189
Jonathan Wilson Avatar answered Oct 26 '22 23:10

Jonathan Wilson