1

I have several views where I'm passing values to an external web service via an ajax post when the user clicks on submit or other action. For the url section of the ajax call I'm trying to pass a key from API.config, located in the Solution Items folder, where the value is different in each build/environment -

Solution Items folder layout

Key I'd like to pass to the ajax url: (API.config)

<appSettings>
    <add key="RestApiEndpointBaseUrl" value="http://devserver/api/" xdt:Locator="Match(key)" xdt:Transform="SetAttributes"/>

Script within the view: (index.cshtml)

<script type="text/javascript">

    var BaseUrl = '@System.Configuration.ConfigurationManager.AppSettings["RestApiEndpointBaseUrl"]';

    $('#login').click(function () {
        var note = {"Account":"@Model.AccountNumber","Text":"Log In","ActionCode":"CW","ResultCode":"LI","SequenceNumber":1,"UserId":"WEB"};
        $.ajax({
            type: "POST",
            data: JSON.stringify(note),
            url: BaseUrl + "Note",
            contentType: "application/json"
        });
    });

</script>

Also, if I add "ToString()" to the end of the variable declaration like this -

var BaseUrl = '@System.Configuration.ConfigurationManager.AppSettings["RestApiEndpointBaseUrl"].ToString()';

I get a NullReferenceException error. Otherwise, I get an empty string for the url. I'm not sure what I'm missing or doing wrong.

How, or Can I properly pass this as the url of the ajax call?

Brian
  • 11
  • 4
  • Possible duplicate of [Access key value from Web.config in Razor View-MVC3 ASP.NET](https://stackoverflow.com/questions/9077764/access-key-value-from-web-config-in-razor-view-mvc3-asp-net) – Robert Moskal Jul 26 '17 at 19:26
  • Actually my issue turned out to be CORS related but I had to end up creating a proxy within the app due to firewall. – Brian Aug 17 '17 at 13:47

0 Answers0