2009-03-04

ASP.NET Resources

Something often overlooked in ASP.NET is the use of Resource files. This common place to store things such as Urls, Variables, and Site Text is an invaluable system built into ASP.NET. This is particularly helpful for things that might change before deployment. Anyway on to code…

Create your an ASP.NET Folder by right clicking on your web project from VS.NET, select “Add ASP.NET Folder”, and select the type of Resource folder that you want--there are some very valuable folders here that you may wish to look into including App_Code and App_Data, but for today let’s add App_GlobalResources.

Add a Resource file to App_GlobalResources, and call it “Constants.resx” [or whatever makes sense for your app].

Open your newly created resource file and add a string to it--naming your string whatever you’d like. I’ve named my string SiteName.

Now, you can use this a couple different ways…

In ASP.NET / Html view (This must be used as the value of Server-side control)

<asp:TextBox runat="server" Text="<%$ Resources:Constants,SiteName %>" />

In your code behind [with intellisense]

string siteName = Resources.Constant.SiteName;

I seem to recall this having a third way to use it, but it’s escaping me now.

Zoidberg away!

No comments: