Friday, 11 February 2011

Asp.Net: Load HTML into Composite Web Server Control

Question:
How to load HTML into web server control?
How to build a composite server control from loaded Html in Asp.Net?
Create WebServerControls dynamically from Html.



Answer:
Inherit from CompositeControl or WebControl.
Implement INamingContainer to route postback events to the right controls.

Override the CreateChildControls method and call

.
Page.ParseControl(youHtml);
...

In WebControls you have to call EnsureChildControls before accessing children.
The CompositeControl ensures this by itself.

Here is an example
public class CustomLayoutControl : CompositeControl, INamingContainer
{
    [Category("Behavior")]
    public string ContentPath
    {
        get
        {
            String s = (String)ViewState["ContentPath"];
            return s;
        }
        set
        {
            ViewState["ContentPath"] = value;
        }
    }
    protected string TemplateContent
    {
        get
        {
            string content = ViewState["TemplateContent"] as string;
            if (content == null)
            {
                content = ReadContentFile();
                ViewState["TemplateContent"] = content;
            }
            return content;
        }
        set
        {
            ViewState["TemplateContent"] = value;
        }
    }
    private string ReadContentFile()
    {
        string temp = "";
        if (!string.IsNullOrEmpty(ContentPath))
        {
            string path = MapPathSecure(ContentPath);
            if (File.Exists(path))
            {
                using (StreamReader sReader = new StreamReader(path))
                {
                    temp = sReader.ReadToEnd();
                }
            }
            else  { /* TODO: log path is wrong */ }
        }
        else { /* TODO: log error: content path is not set */}
        return temp;
    }

    protected override void OnLoad(EventArgs e)
    {
        EnsureChildControls();
        base.OnLoad(e);
    }
    /// 
    /// Reads the template
    /// 
    protected override void CreateChildControls()
    {
        Control control = Page.ParseControl(TemplateContent);
        this.Controls.Add(control);
        base.CreateChildControls();
    }
}

No comments: