How to read web.config APP key settings in HTML markup

我们两清 提交于 2019-11-30 11:47:09
Scott Mitchell

In addition to using <%=ConfigurationManager.AppSettings["MyAttribute"]%>, as others have noted, you can also use expression builders. The syntax is a little different. Instead of <%=...%> you use <%$ AppSettings: MyAttribute %>, like so:

<object id="myObjectID attr="<%$ AppSettings: MyAttribute %>" ...>

If you are just dumping an appSettings value directly into static HTML (as I presume you are in this example), these two approaches are identical for all practical purposes.

What is nice about expression builders, though, is that you can use them to declaratively assign appSettings values to Web control properties, something you cannot do with the <%=...%> syntax. That is, with expression builders you can do something like:

<asp:Label runat="server" ... Text="<%$ AppSettings: MyAttribute %>" />

Whereas you could not do:

<asp:Label runat="server" ... Text="<%=ConfigurationManager.AppSettings["MyAttribute"]%>" />
huysorng

The following code:

<%$ AppSettings: MyAttribute %>

is not compatible with general HTML markup and JavaScript function! It's good for asp tag.

Whereas

<%=ConfigurationManager.AppSettings("MyAttribute")%>

really work in general HTML markup.

so

<%=ConfigurationManager.AppSettings("MyAttribute")%>

is my recommendation!

You can use the ConfigurationManager in you ASPX page. Then you can add in your OBJECT tag parameters:

Web.Config

</configuration>
    <appSettings>
        <add key="Setting" value="Value"/>
    <appSettings>
</configuration>

ASPX

<object>
    <param name="Setting" value="<%= System.Configuration.ConfigurationManager.AppSettings["Setting"] %>" />
</object>

I suggest you generate your OBJECT tag dynamically at run-time from the server. This way you can inject whatever parameters you read from the web.config file.

Ender

You have a few options. If you add the runat="server" attribute to your object tag, you can access it from your codebehind using its ID, and add attributes that way:

myObjectID.Attributes.Add("attrName", "value")

If you don't want to do that, you could use inline literals:

<object id="myObjectID attr="<%= ConfigurationManager.AppSettings("MyAttribute") %>" ...>

Either way should get the job done.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!