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>
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With