user386167
user386167

Reputation:

Passing AppSettings to external javascript file the MVC way?

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.

Upvotes: 1

Views: 1330

Answers (1)

Dan Atkinson
Dan Atkinson

Reputation: 11728

You could send them via a JsonResult?

In your JS, you'd have a request which sends a GET/POST request to a particular action (let's call it GetAppSetting(), and the corresponding value is returned in the response.

For security reasons, I would restrict what can be requested though...

public JsonResult GetAppSetting(string id)
{
  //You could check what's been requested here if you want to make sure you're only returning information that you may not wish to send.
  string appSetting = AppSettings[id];

  if(string.IsNullOrEmpty(appSetting) == false)
  {
    return Json(appSetting, JsonRequestBehavior.AllowGet);
  }

  //Handle non-existent settings here...
  throw new Exception("This setting does not exist");
}

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...

public JsonResult GetAppSettings()
{
  var appSettings = new Dictionary<string, string>();
  appSettings.Add("myAppSetting1", AppSettings["myAppSetting1"]);
  appSettings.Add("myAppSetting2", AppSettings["myAppSetting2"]);
  appSettings.Add("myAppSetting3", AppSettings["myAppSetting3"]);

  return Json(appSettings, JsonRequestBehavior.AllowGet);
}

Note the JsonRequestBehavior.AllowGet in the JsonResults (MVC 2 only). This is because, by default, ASP.NET MVC 2 will not allow GET requests 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.

Upvotes: 3

Related Questions