简体   繁体   中英

asp.net normal html input runat=“server” return non-updated value in code-behind

I have edit server detail page called editServer.aspx. On page load, I retrieve data from database and set value to textbox. When user clicks save button, the value from textbox is empty or not updated to new value that users key in.

part of code in .aspx

<input type="text" class="form-control" id="serverRemarksTB" name="serverRemarksTB" 
       placeholder="general server remarks" runat="server"/>
<asp:Button ID="editPhysicalServerBtn" runat="server" Text="Save" class="btn btn-success"
  style="padding-left:30px; padding-right:30px;" onclick="editPhysicalServerBtn_Click" />

in .aspx.cs

 protected void Page_Load(object sender, EventArgs e)
 {
    //code to retrieve data from database and store in server instance
    serverRemarksTB.Value = server.remarks;
 }        
 protected void editPhysicalServerBtn_Click(object sender, EventArgs e)
 {      
     string remarks = serverRemarksTB.Value; //this is not updated.  
 }

For example, in database the server remarks is "do not shutdown". So when I open the .aspx page, I will see the textbox with "do not shutdown". When I change the value to "can shutdown" and click Save button, in aspx.cs server remarks value remains the same - "do not shutdown".

It's because everytime you load the page you override the value of the input with this line of code...

serverRemarksTB.Value = server.remarks;

and based on the ASP.NET Pipeline Lifecycle , Page_Load is executed first and then controls' event handlers. To avoid that you will need to run the above mentioned line of code only when the page first load...on a GET request and not on a POST request. You can change the Page_Load event handler like this...

protected void Page_Load(object sender, EventArgs e)
{
        //code to retrieve data from database and store in server instance
        if(!IsPostBack)
            serverRemarksTB.Value = server.remarks;
 }

Use IsPostBack clause or every time your page loads your textbox will be populated from database value .

When you click save button , it causes postback which causes your serverRemarksTB value again to "do not shutdown" .

if(!Page.IsPostBack)
{
serverRemarksTB.Value = server.remarks;
}

That's because your page_Load serverRemarksTB.Value = server.remarks; code is not wrapped in IsPostback block. So when you post your form back the value of the text box gets updated to database value. You should put your database code inside IsPostback check. Like

 if(!IsPostBack)
    {
       serverRemarksTB.Value = server.remarks;
    } 

in the Page_Load method.

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