简体   繁体   English

(ASP.NET)在 Page_Load() 开始时更改输入,然后在表单提交后检索输入值给出旧值

[英](ASP.NET) Changing an input at the start of Page_Load() and then retriving the input value after form submit gives the old value

I have a form that is supposed to have defalt values, which the user can decide to change in some fields.我有一个应该具有默认值的表单,用户可以决定在某些字段中进行更改。 The inputs are set up like this:输入设置如下:

<input type="text" id="username" clientidmode="static" runat="server" />

I am setting the default data at the start of Page_Load() like this:我在 Page_Load() 的开头设置默认数据,如下所示:

username.Value = "test"

And I'm getting the values later in if(isPostBack) like this:我稍后会像这样在 if(isPostBack) 中获得这些值:

string sUsername = username.Value;

The idea is that they will be able to change certain values about the user, or just leave the default values if they don't want to change that field.这个想法是,他们将能够更改有关用户的某些值,或者如果他们不想更改该字段,则只需保留默认值。

The issue is that when I'm getting the field values in if(isPostBack) I'm just getting the values I've set at the start of Page_Load() even if the user changed the form values.问题是,当我在 if(isPostBack) 中获取字段值时,我只是获取在 Page_Load() 开始时设置的值,即使用户更改了表单值。

What am I doing wrong?我究竟做错了什么?

Here is a simple way to reproduce this.这是重现此问题的简单方法。 Create an asp.net project and add a WebForm.创建一个 asp.net 项目并添加一个 WebForm。

Then add this to the page:然后将其添加到页面:

<input type="text" id="username" runat="server" />
<input type="submit" />

and add this to the code behind:并将其添加到后面的代码中:

protected void Page_Load(object sender, EventArgs e)
{
     username.Value = "Test";

     if (IsPostBack)
     {
          string sUsername = username.Value;
     }
 }

Your variable declaration should be inside !IsPostBack你的变量声明应该在里面!IsPostBack

if(!IsPostBack)
{
    username.Value = "test"
}
  • The issue is that as soon as you click on something else, your page load event triggers and your page loads first then your button click event occurs.问题是,一旦您单击其他内容,您的页面加载事件就会触发并且您的页面首先加载,然后您的按钮单击事件就会发生。

  • You have put the !IsPostBack at the wrong place.您将 !IsPostBack 放在了错误的位置。 You need to keep the default data at the start of Page_Load() inside !IsPostBack(), then get the values later anywhere you want, inside any button_click event.您需要在 !IsPostBack() 内的 Page_Load() 开始处保留默认数据,然后在任何 button_click 事件内的任何您想要的地方获取值。

  • Have a look at this page: Edit Textbox not working (It is not taking the new data inserted and submitted)看看这个页面: Edit Textbox not working(它不接受插入和提交的新数据)

Although, if you could have given some better view of code it would have been easy to tell.虽然,如果您可以更好地查看代码,那将很容易分辨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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