views:

325

answers:

1

I would like to expose a complex property from a custom ASP.NET user control, in such a way that it can be set from the control tag in the aspx page.

Something like this:

public class TestData {
    public int X;
    public int Y;
}

public partial class TestControl : System.Web.UI.UserControl {

    public TestData TestProperty {
        get {
            return ViewState["TestProperty"] as TestData;
        }
        set {
            ViewState["TestProperty"] = value;
        }
    }
}

And then in the .aspx file of a page that contains the control I would like to have something like:

<div>
    <testns:TestControl runat="server" ID="TestControl1" TestProperty="X:1,Y:2"/>
</div>
+5  A: 

Sorry for answering my own question, but I've found out a couple of ways of doing that, and I thought they might be useful for someone else as well :)

To serialize the object in an attribute of the control, you have to define an appropriate TypeConverter, and apply a TypeConverterAttribute to the property type. Here is an example: How to: Implement a Type Converter.

Even easier, you can persist the attribute in the control's content just like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="wbctrlstst._Default" %>
<%@ Register TagPrefix="x" TagName="TestControl" Src="~/TestControl.ascx" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
    <form id="form1" runat="server">
    <div>
        <x:TestControl runat="server" ID="testlist1">
            <TestProperty X="1" Y="42" />
        </x:TestControl>
    </div>
    </form>
</body>
</html>

The only requirement, for what I could see, is that the type must have a default constructor. You can apply the PersistenceModeAttribute to the property to specify that the property should be persisted in the controls's contents, but it looks like it's the default behavior, and this is not strictly needed.

[PersistenceMode(PersistenceMode.InnerProperty)]
public TestData TestProperty {
    get {
        return ViewState["TestProperty"] as TestData;
    }
    set {
        ViewState["TestProperty"] = value;
    }
}
Paolo Tedesco
Sorry for my answer then. I was so sure that you couldn't do this (I don't use webforms anymore though).
Mattias Jakobsson
@Mattias: don't worry, I guess you were just trying to be helpful :)
Paolo Tedesco