1

This seems like an elementary issue but it has me stumped.

I have a main page which loads a custom control (.ascx) on page_load.

This custom control has two fields. One of them being a dropdownlist and the other being a text box. When the dropdownlist changes value it triggers a post back, some logic is executed server side and a value is generated for the textbox. I stepped through the code and the value is created and assigned correctly. However, when the page is rendered the value does not change.

If I change the textbox value to "QQQ" and trigger the postback, "QQQ" stays in the textbox so I can verify viewstate is working.

Is there any reason why the generated value is not being displayed in the form on postback. This process works fine on the initial page load.

.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
   string ascxPath = @"~/_CONTROLTEMPLATES/TRC_BITS.ascx";
   TRC_BITS control = Page.LoadControl(ascxPath) as TRC_BITS;
   phForm.Controls.Add(control);
}

.ascx

   <asp:TextBox ID="message" runat="server" TextMode="MultiLine" /><br/>
   <asp:DropDownList ID="year" runat="server" AutoPostBack="true">
      <asp:ListItem Text="2011">2011</asp:ListItem>
      <asp:ListItem Text="2012">2012</asp:ListItem>
      <asp:ListItem Text="2013">2013</asp:ListItem>
   </asp:DropDownList>

.ascx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        year.SelectedValue = DateTime.Now.Year.ToString();
    }
    if (year.SelectedValue == 2012)
       message.Text = "ABC";
    else
       message.Text = "XYZ";
}
4

2 に答える 2

4

これらのコントロールをページに動的に追加するため、ユーザーコントロールにIDを割り当てる必要があります。ページがポストバックされるたびに、必ず同じIDをコントロールに割り当ててください。そうすると、フィールドはViewStateから再入力されます。

OnInitまた、Shaiが提案したように、の代わりに中にコントロールをロードした方が適切ですPage_Load。ユーザーコントロールでは状況が少し異なりますが、一般的には、LoadViewStateメソッドを実行する前に動的コンテンツを追加する必要があります。

ここに画像の説明を入力してください

動的コンテンツの永続化の問題を解決するための何かを探している場合は、DynamicControlsPlaceHolderを確認することをお勧めします。

于 2012-05-10T16:03:18.177 に答える
2

コントロールを動的に追加しているため、ページの oninit イベント中にコントロールを追加する必要があります。試してみてください、私を信じてください。頑張れ。ヤラ。

于 2012-05-10T16:11:05.363 に答える