Get value from web.config applicationSettings into ASP.NET markup

这一生的挚爱 提交于 2019-11-30 19:25:40

Typically you would create a custom settings class to read these values out as this artical describes. Personally, I would just use the appSettings as suggested above as this is existing functionality and for what your doing would on the surface seem adequate.

However, not knowing your circumstances, what your attempting to do could be solved without the custom settings like so:

In the code behind I created a protected function to retrieve the setting

protected string GetCustomSetting(string Section, string Setting)
{
    var config = ConfigurationManager.GetSection(Section);

    if (config != null)
        return ((ClientSettingsSection)config).Settings.Get(Setting).Value.ValueXml.InnerText;

    return string.Empty;
}

Then in the aspx markup I call this function

<div>
    <label runat="server" id="label"><%=GetCustomSetting("applicationSettings/MyApp.Properties.Settings", "ImagesUrl") %></label>
</div>

Hope this helps.

Follow Up:

The CodeExpression will look something like this:

public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
    var config = ConfigurationManager.GetSection("applicationSettings/MyApp.Properties.Settings");
    return new CodePrimitiveExpression(((ClientSettingsSection)config).Settings.Get(entry.Expression).Value.ValueXml.InnerText);
}

In my Test, I created a class called CustomSettingsExpressionBuilder and added it to the App_Code folder. Added the configuration for the custom express to the web.config and called it from aspx like so:

<asp:Label ID="Label1" runat="server" Text="<%$CustomSettings:ImagesUrl %>"></asp:Label>

Does it has to be in markup? Why don't you set it in code-behind.

Image1.ImageUrl= //fetch your settings here.

One another way would be defining a property or static method in your code-behind and then using that in the markup.

I'm not sure about the ASP.NET bit of it, but if this was normal code you'd do MyApp.Properties.Settings.Default.ImagesUrl, so try

<asp:Image ID="Image1" runat="server" 
           ImageUrl="<%$MyApp.Properties.Settings.Default.ImagesUrl%>

It would definitely be easier to store this in <appSettings> though.

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