Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom elements in ASP.NET with custom child-elements

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?

like image 667
Jan Aagaard Avatar asked Mar 23 '09 13:03

Jan Aagaard


2 Answers

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>
like image 84
Aleris Avatar answered Nov 09 '22 13:11

Aleris


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace ComponentDemo
{
    [ParseChildren( true )]
    public class MyGraph : System.Web.UI.WebControls.WebControl
    {
        private List<Color> _colors;

        public MyGraph() : base() { ;}

        [PersistenceMode( PersistenceMode.InnerProperty )]
        public List<Color> Colors
        {
            get 
            {
                if ( null == this._colors ) { this._colors = new List<Color>(); }
                return _colors; 
            }
        }
    }

    public class Color
    {
        public Color() : base() { ;}
        public string Value { get; set; }
    }
}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ComponentDemo._Default" %>
<%@ Register Assembly="ComponentDemo" Namespace="ComponentDemo" TagPrefix="my" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <my:MyGraph runat="server">
            <Colors>
                <my:Color Value="value1" />
                <my:Color Value="value2" />
                <my:Color Value="value3" />
                <my:Color Value="value4" />
            </Colors>
        </my:MyGraph>
    </div>
    </form>
</body>
</html>
like image 40
Mika Karjunen Avatar answered Nov 09 '22 13:11

Mika Karjunen