I have created a custom web server control in asp.net. I am trying to render a List of a class in the RenderContents method.
Here is my code:
[DefaultProperty("Items")]
[ToolboxData("<{0}:News runat=server></{0}:News>")]
public class News : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public List<NewsItem> Items
{
get
{
List<NewsItem> items = (List<NewsItem>)(ViewState["Items"] == null ? new List<NewsItem>(): ViewState["Items"]);
return items;
}
set
{
ViewState["Items"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
foreach (var item in Items)
item.RenderControl(output);
}
}
<Aram:News ID="News1" runat="server" />
Cannot create an object of type 'System.Collections.Generic.List`1[[AramWebControls.NewsItem, Custom Web Server Control, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' from its string representation '(Collection)' for the 'Items' property.
<Aram:News ID="News1" runat="server" Items="(Collection)" />
I found the solution for this problem. First of all, the Items are of type List and that is a collection. It can not be persisted inside the News control tag. So it has to be a part of the content of News control tag. This calls for custom viewstate management.
For details you can first refer to Web Control Collection Property Example And then you need to override LoadViewState , SaveViewState and TrackViewState to handle the items. For more info on this one refer to Server Control Properties Example