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?
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>
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>
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