Tuesday, 2 December 2008

Dynamic Data - Updated URL FieldTemplate

Sorry I’ve been quiet for such a long time but towards the end of October I was helping out with a local charity and in early November I started some Freelance Web Development in DD, so from now on the posts will still come but will be a bit more infrequent (except when there is some new stuff to get our teeth into)

So improving the Url FieldTemplate, here’s what you see if you use the URL FieldTemplate as is from DD Futures:

ScreenShot004

Figure 1 – Standard Url FieldTemplate

And here’s what I want to see

ScreenShot142

Figure 2 – Improved Url FieldTemplate

Here’s the code:

<%@ Control 
    Language="C#" 
    CodeFile="Url.ascx.cs" 
    Inherits="Url" %>

<asp:HyperLink 
    ID="HyperLinkUrl" 
    runat="server" 
    Target="_blank" />

Listing 1 – Url.ascx file

public partial class Url : System.Web.DynamicData.FieldTemplateUserControl
{
    protected override void OnDataBinding(EventArgs e)
    {
        string url = FieldValueString;
        if (!(url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || 
url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) { url = "http://" + url; } HyperLinkUrl.NavigateUrl = url; // set display text of the url HyperLinkUrl.Text = String.IsNullOrEmpty(Column.GetUrl())?
FieldValueString : Column.GetUrl(); } public override Control DataControl { get { return HyperLinkUrl; } } }

Listing 2 – Url.ascx.cs file

public class UrlAttribute : Attribute
{
    public String Text { get; private set; }

    public UrlAttribute(string text)
    {
        Text = text;
    }
    public static UrlAttribute Default = new UrlAttribute(String.Empty);
}

public static partial class HelperExtansionMethods
{
    public static String GetUrl(this MetaColumn column)
    {
        return column.Attributes.OfType<UrlAttribute>().DefaultIfEmpty(UrlAttribute.Default).First().Text;
    }
}

Listing 3 – UrlAttribute and Helper method.

[Url("Insert New Products")]
public Object InsertProducts

Listing 4 – Sample use of attributes

Now if there’s no UrlAttribute then you get the standard format but when there is a UrlAttribute present then you get the display text of  the HyperLink as that of the UrlAttribute.

I though in a future article I could assign the display text of the Url FieldTemplate to another field thus making it a bit more dynamic, but that’s for another time.

No comments: