Reputation: 746
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".
Upvotes: 1
Views: 2641
Reputation: 14830
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;
}
Upvotes: 4
Reputation: 1447
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.
Upvotes: 1
Reputation: 4069
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;
}
Upvotes: 2