简体   繁体   中英

How to preserve user input in literal control on postback?

On Page_Init, if is post back, I check if a button called Button1 was clicked, if so I add a LiteralControl to a Panel called Panel1:

Panel1.Controls.Add(new LiteralControl("Enter Code:<input type=\"text\" name=\"txtCode\"></td>"));  

As you can see, it is just the text "Enter Code:" followed by a TextBox called txtCode.

I have a second button (Button2) that, when clicked, I would like to retrieve the text entered in txtCode:

protected void Button2_Click(object sender, EventArgs e)
    {
        foreach (Control c in Panel1.Controls)
        {
            if (c is LiteralControl) ...                
        }
    }

I'm not sure how to do this... How can I get the text entered in txtCode?

You can always use the Request.Form collection:

string txtCode = Request.Form["txtCode"];

It will contain all values posted with the current request, regardless of being server side controls or not.

The generated input doesn't persist its value after turn around (HTTP GET then POST) because it is not System.Web.UI.Control that has ViewState. So the value that user enters is in form collection and you can try to get it from there (Request.Form), but an easier way is to add a TextBox in Init(..). After that a ViewState of the textbox should be loaded on POST and you can access user's input in its Text property.

In Init():

_MyTextBox = new TextBox();
panel1.Controls.Add(_MyTextBox);

In Button_Click:

var value = _MyTextBox.Text ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM