开发者

ASP.Net ITemplate - how do i read the raw content defined inside

开发者 https://www.devze.com 2022-12-26 18:30 出处:网络
i have situation where in i would like to read the content of the ITemplate. for example i 开发者_如何学JAVAhave something like

i have situation where in i would like to read the content of the ITemplate.

for example i 开发者_如何学JAVAhave something like

<WD:PopUpPanel runat="server" ID="MyPoPUp">
<InitScript>
    // javascript
    document.getElementByID('urName').value = 'enter your name';
</InitScript>
<Content>
    Name:<asp:TextBox runat="Server" ID="urName"/>
</Content>
</WD:PopUpPanel>

basically the contents inside the InitScript is some javascript, which i want to use in ScriptManager.RegisterScript.

so my question is how do i define InitScript???

i tried

public ITemplate InitScript;

this gives me CompiledTemplateBuilder object, how do i read the content inside InitScript ???

thanks for reading, any help would be highly appreciated...


Firstly you need to instantiate your template into a template container control.

Below is an example of doing this - a user control with InitScript property; this template is being instantiated in the control's OnPreRender method. After this you could just add this template control to the user control child control collection or, as you asked in your question, render it as a string (I use my RenderControl utility method to render control as a string):

public class MyControl : UserControl
{
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate InitScript { get; set; }

    protected override void OnPreRender(EventArgs e)
    {
        if (this.InitScript != null)
        {
            Control templateContainer = new Control();
            InitScript.InstantiateIn(templateContainer);
            //Controls.Add(templateContainer);

            // here is "a raw" content of your template
            var s = RenderControl(templateContainer);
        }
    }

    private string RenderControl(Control control)
    {
        StringBuilder sb = new StringBuilder();
        using (StringWriter stringWriter = new StringWriter(sb))
        {
            using (HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter))
            {
                control.RenderControl(textWriter);
            }
        }

        return sb.ToString();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号