views:

299

answers:

2

I know that it is possible to define custom tags in ASP.NET with User Controls. But as far as I know you can only add attributes to these controls. I would like to be able to embed more complex data, a bit lite this:

<myControls:MyGraph id="myGraph1" runat="server">
   <colors>
     <color>#abcdef</color>
     <color>#123456</color>
   </colors>
</myControls:MyGraph>

It this possible in ASP.NET? Should I try to extend a ListView? Or it there a better and more correct solution?

+3  A: 

It is certainly possible. For your example the classes would look like:

[ParseChildren(true)]
class MyGraph : WebControl {
    List<Color> _colors = new List<Color>();
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public List<Color> Colors {
        get { return _colors; }
    }
}

class Color {
    public string Value { get; set; }
}

And the actual markup would be:

<myControls:MyGraph id="myGraph1" runat="server">
   <Colors>
     <myControls:Color Value="#abcdef" />
     <myControls:Color Value="#123456" />
   </Colors>
</myControls:MyGraph>
Aleris
Thanks for this.. It's really hard with all the jargon concerning hand-built server controls to get a straight answer. In hindsight treating the inner elements as properties and nother else makes a lot of sense. Cheers!
CResults
A: 

When I try to implement the above, it gives me Object reference not set to an instance of an object" at MyControls:Color.

Here's my code.

My code behind:

<ParseChildren(True)> _
    Partial Class WebForm
    Inherits System.Web.UI.UserControl

    Private _formtitle As String = String.Empty
    Private _items As New List(Of FormField)

    <PersistenceMode(PersistenceMode.InnerProperty)> _
        Public ReadOnly Property Items() As List(Of FormField)
        Get
            Return _items
        End Get
    End Property

End Class

Public Class FormField
    Private _fieldname As String = String.Empty
    Private _required As Boolean = False
    Private _instructions As String = String.Empty
    Private _ishtml As Boolean = False

    Public Property FieldName() As String
        Get
            Return _fieldname
        End Get
        Set(ByVal value As String)
            _fieldname = FieldName
        End Set
    End Property

    Public Property Required() As Boolean
        Get
            Return _required
        End Get
        Set(ByVal value As Boolean)
            _required = value
        End Set
    End Property

End Class

Please help.

kago
@kago: This is not an answer but a new question, so you should first search a solution and if none is found then create a new question.
Jan Aagaard