How to put server-side control in Literal?

非 Y 不嫁゛ 提交于 2019-12-13 07:00:37

问题


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);


来源:https://stackoverflow.com/questions/9101804/how-to-put-server-side-control-in-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!