How to put server-side control in Literal?

2019-08-21 18:39发布

问题:

I want put a server-side control in a Literal. Is it possible? If yes, how? I know the description of the class says it all:

Represents HTML elements, text, and any other strings in an ASP.NET page that do not require processing on the server

回答1:

If you want to be wrapping server side code in other controls you probably want to be using Panel. As the comments have already stated, it is impossible to treat literal text as a server side Control.



回答2:

Funny this comes up as I just looked through some of my old code yesterday. Literals can do this. I did this originally to emit user controls through a web service call from Javascript(yikes, I know...it was fun) but this will fit your needs as well.

    protected void Page_Load(object sender, EventArgs e)
    {
        litTest.Text = RenderUserControlAsString("WebUserControl1.ascx");
    }

    private string RenderUserControlAsString(string path)
    {
        Page page = new Page();
        UserControl control = (UserControl)page.LoadControl(path);

        //add the control to the page
        page.Controls.Add(control);

        StringWriter sw = new StringWriter();
        HttpContext.Current.Server.Execute(page, sw, true);

        //return the rendered markup of the page, which only has our single user control
        return sw.ToString();
    }

Throw your literal on the page and assign it's text value to RenderUserControlAsString("Path to your User Control"). With that said, in your user control you must wrap child controls within a form control.

<form runat="server"> <asp:TextBox id="txtTest" Text="From User Control" runat="server"  /> </form>

I hope that helps!



回答3:

TextBox myTextBox = new TextBox();
YourLiteralID.Controls.Add(myTextBox);