Tuesday, 24 February 2009

Static links for aspx pages in 20 lines of code

Still using WebForms? Sick of magic string URLs that break when you move you ASPX pages around? Try this! I've created a class called UrlFor<TSomePage>. It examines the page class and figures out the URL by making a few assumptions about your aspx pages (the aspx file has the same name as the class, the namespaces match the folder structure, that kind of thing...)

public class UrlFor<TAspxPage>
    where TAspxPage : Page
    private static string baseUrl = typeof(TAspxPage).FullName.Substring("YourAppBaseNamespace".Length).Replace('.', '/') + ".aspx";

    public Dictionary<string, string> QueryString = new Dictionary<string, string>();

    public UrlFor<TAspxPage> Set<TValue>(Expression<Func<TAspxPage, TValue>> getProp, TValue value)
    {
        this.QueryString[((MemberExpression)getProp.Body).Member.Name] = value.ToString();
        return this;
    }
    public override string ToString()
    {
        var qs = String.Join("&", this.QueryString.Select(pair =] pair.Key + "=" + HttpUtility.UrlEncode(pair.Value)).ToArray());
        return baseUrl + (qs.Length ] 0 ? ("?" + qs) : String.Empty);
    }
}
anyway, it lets you write things like this in your code:
[%= new UrlFor<Meetings.Details>().Set(d => d.WorkspaceId, 1).Set(d => d.MeetingId, 2) %>
where Meeting.Details is a Page class with a property on it called MeetingId and one called WorkspaceId. This generates a url like
/Meetings/Details.aspx?WorkspaceId=1&MeetingId=2
Of course your pages may not have properties that correspond to the querystring parameters, but you can always write an extension like
public static class UrlForExt
{
    public static UrlFor<T> SetWorkspaceId<T>(this UrlFor<T> url, int value)
        where T:WorkspacePage
    {
        url.QueryString["workspaceid"] = value.ToString();
        return url;
    }
}
and get the same effect by writing something like
new UrlFor<Default>().SetWorkspaceId(1)
Neat huh!? Use this to build your links and you can rename and move your pages to your hearts content!

Submit this story to DotNetKicks

0 comments:

Post a Comment