Wednesday, 14 January 2009

Dynamic Data – Default Value in ForeignKey Edit FieldTemplate

This article simply show how to get the DefaultValueAttribute to affect the ForeignKey Edit FieldTemplate.

So the first thing is to set some Metadata up.

[MetadataType(typeof(Order_DetailMD))]
public partial class Order_Detail
{
    public class Order_DetailMD
    {
        [DefaultValue("15")] // Genen Shouyu
        public object Product { get; set; }
    }
}

Figure 1 – Metadata

Now all we need to do is add a small amount of code to the OnDataBinding event handler of the ForeignKey Edit FieldTemplate.

protected override void OnDataBinding(EventArgs e)
{
    base.OnDataBinding(e);

    if (Mode == DataBoundControlMode.Edit)
    {
        string foreignkey = ForeignKeyColumn.GetForeignKeyString(Row);
        ListItem item = DropDownList1.Items.FindByValue(foreignkey);
        if (item != null)
        {
            DropDownList1.SelectedValue = foreignkey;
        }
    }
    // set the default value
    if (Mode == DataBoundControlMode.Insert)
    {
        var defaultValue = Column.Attributes.OfType<DefaultValueAttribute>().FirstOrDefault();
        if (defaultValue != null)
        {
            ListItem item = DropDownList1.Items.FindByValue(defaultValue.Value.ToString());
            if (item != null)
                DropDownList1.SelectedValue = defaultValue.Value.ToString();
        }
    }
}

Figure 2 – Setting the default value

Here the line in BOLD ITALIC font are to be added.

Here what happens is when the template is in Insert mode the an attempt is made to get the DefaultValueAttribute from the Column property, if this is not null then the value is retrieved and then an attempt is made at finding it in the DropDownList1 . If it is found then the drop down list is set to it.

I hope that's not too much explanation.

4 comments:

Anonymous said...

is this for dynamic entities or linqto sql?

Steve said...

I should work with both, as there are no Linq Expressions.

Steve :D

nkstr said...

Man you are HAL on asp.net dynamic data as far as I'm concerned (only without the creepy "I am gonna frickin kill your ass in outer space" part).

Thanks for sharing your vast knowledge in this field!

Steve said...

:D LOL