Flidge
Flidge

Reputation: 1

Define a Color in web.config and use it in CSS file

i want to save a color in the web.config file and use it in the CSS file, to use it for different web apps. e.g.: Web app 1 has a blue design, Web app 2 has a green design ... I the web.config it looks like this:

<add key="name" value=" #000000"/>

My question is, how can i get this value in the CSS file.

Upvotes: 0

Views: 2139

Answers (2)

phantomflash
phantomflash

Reputation: 124

I also got an error when I tried Tim Gerhard's solution. (I can't enter this as a comment to that answer because I'm a relatively new user.) After several iterations, I made it work (in an actual inline style), like this:

<!-- In web.config -->
<appSettings>
    <add key="PageTitleStyle" value="style='color:red'"/>
</appSettings>

<!-- In the .aspx file -->
<span <asp:Literal runat="server" Text="<%$ AppSettings:PageTitleStyle %>" /> >
      Page Title Text Here</span>

Note that in my actual application, I also get the page title text itself from Web.config, using the same syntax with a separate "add key" string.

It would also be valid, and often considered preferable, in an "internal style sheet" form as Tim illustrates. In fact, re-reading your question, I think you'll want to do it that way.

I tried it with just the string "red" in the key, but it wouldn't let me splice that into the inline style tag after "color:". So I ended up with the entire style string in Web.config. I didn't try it in an "internal style sheet" context, but it's just different enough that it might work.


Supplemental information - In answer to Tim's question about the errors I received trying his construct (using Visual Studio 2013 and .Net 4). First I got:

The expression prefix 'ConfigurationManager.AppSettings' was not recognized. Please correct the prefix or register the prefix in the section of configuration.

When I removed "ConfigurationManager." then I got:

The expression '<%$ AppSettings['PageTitleStyle'] %>' is invalid. Expressions use the syntax <%$ prefix:value %>.

So then I changed the square bracket construct to use a colon. Then I got ("blockquote" doesn't work right with this one, so I'm using "code sample" formatting):

Literal expressions like '<%$ AppSettingsa:PageTitleStyle %>' are not allowed.
Use <asp:Literal runat="server" Text="<%$ AppSettingsa:PageTitleStyle%>" /> instead.

So that led me to the working syntax above.

Upvotes: 2

Tim Gerhard
Tim Gerhard

Reputation: 3587

You will need to use inline stylings to set webconfig values in your css file. Like this:

<style type="text/css">
        .yourClass {
            color: <%= ConfigurationManager.AppSettings["YOURKEYNAME"] %>;
        }
</style>

You could add it in your razor Master template for example.

You can read more about this here: https://forums.asp.net/t/1349824.aspx?How+to+set+CSS+color+settings+from+web+config

Upvotes: 0

Related Questions