Mike Pennington
Mike Pennington

Reputation: 676

Accessing app setting from aspx and add concatenated text

I've got a project where I'm tasked with changing hard-coded domain references from one domain to another in a group of legacy C#/VB web projects. I want to parameterize the domains as much as possible instead of just replacing with a different hard-coded value. The problem is that there are over 800 of these references in about 30 different solutions, so creating variables in each code-behind to bind to would take forever.

I have added the new domains to the appSettings section of the web.config file, and this works:

<asp:HyperLink Text="Link" NavigateUrl="<%$appSettings:DomainX %>" runat="server" />

But I need to be able to do something like this:

<asp:HyperLink Text="Link" NavigateUrl="<%$appSettings:DomainX %>/newPage.aspx" runat="server" />

But when I add the "/newPage.aspx" the page doesn't compile anymore. I don't really care if this is done with an asp:HyperLink tag or just a tag.

Any ideas on how I can accomplish this?

Thanks.

Upvotes: 4

Views: 4107

Answers (3)

rsbarro
rsbarro

Reputation: 27339

I think you have two options. The easiest is to just use a plain old anchor tag, if you're not doing anything with the HyperLink server side:

<a href="<%= string.Concat(ConfigurationManager.AppSettings["DomainX"], "/newPage.aspx") %>">Link</a>

Alternatively, you could set the NavigateUrl in the Page_Load, since <%= will not work properly within the HyperLink server tag:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
        link1.NavigateUrl = string.Concat("http://", 
                  ConfigurationManager.AppSettings["DomainX"], "/newPage.aspx");
}

You could also see if you can make a custom binding, something like $myBinding:DomainX, but I don't know if that's possible off the top of my head (I would assume it is though).

EDIT
That $appSettings:DomainX code is called an ASP.NET Expression, and can you can create custom expressions. This post from Phil Haack covers how to set them up, in case you are interested.

Upvotes: 6

Shadow Wizard
Shadow Wizard

Reputation: 66388

I would go with one of two different approaches that would save you the need to change the NavigateUrl in the .aspx itself.

One option is to inherit from HyperLink class and overriding the NavigateUrl property, adding the ConfigurationManager.AppSettings["DomainX"] in the getter method. Having this, just change <asp:HyperLink ... to <UC:MyLink ...

Second option is adding small function to each page (can be in one shared place and just called from each page) that will iterate over all the hyperlinks controls and dynamically add the domain. To find all controls of certain type you can use such code for example.

Upvotes: 0

How about something along the lines of:

<%=ConfigurationManager.AppSettings["DomainX"].ToString() + "/newPage.aspx" %>

Upvotes: 2

Related Questions