[英]SelectetValue does not return the selected value in ASP.NET DropDownList
I'm slowly going mad over the following problem: In my ASP.NET page (target: .NET 4.0) I have the following declaration of a DropDownList
: 我对以下问题感到非常生气:在我的ASP.NET页(目标:.NET 4.0)中,我具有以下
DropDownList
声明:
<asp:DropDownList ID="cmbRequestState" runat="server" EnableViewState="true">
<asp:ListItem Text="Pending" Value="0"></asp:ListItem>
<asp:ListItem Text="Open" Value="1"></asp:ListItem>
<asp:ListItem Text="Closed" Value="2"></asp:ListItem>
</asp:DropDownList>
In the Page_Load
event in code-behind I set the cmbRequestState
value to "2" for example - everything's fine, the value shown in the combo box in the browser is "Closed", as the respective <option>
tag in HTML has the selected="selected"
attribute. 例如,在代码隐藏的
Page_Load
事件中,我将cmbRequestState
值设置为“ 2”-一切都很好,浏览器组合框中显示的值是“ Closed”,因为HTML中的各个<option>
标记均已selected="selected"
属性。
Then I select "Open" and perform a postback using a "Save"-button on my page. 然后,选择“打开”并使用页面上的“保存”按钮执行回发。 When I retrieve the
SelectedValue
for cmbRequestState
in the button's code, it is still "2" even though I've selected "1". 当我在按钮的代码中检索
cmbRequestState
的SelectedValue
,即使我选择了“ 1”,它仍然是“ 2”。
Now I don't write ASP.NET applications too often, but I do have some knowledge in HTML and PHP programming and from my WinForms and WPF background I'd expect the SelectedValue
to contain the value that is currently selected... Also, I do not want to perform a postback every time a user selects a value from the list. 现在,我不再经常编写ASP.NET应用程序,但是我确实对HTML和PHP编程有所了解,从WinForms和WPF背景中,我希望
SelectedValue
包含当前选定的值...而且,我不想每次用户从列表中选择一个值时都执行回发。
What am I missing here? 我在这里想念什么? How would I make sure that when opening the page, the current request state is selected and still get the new selection if the user makes a change?
我如何确保在打开页面时选择当前请求状态,并且如果用户进行了更改,仍然可以得到新的选择?
According to the page lifecycle , the selectedvalue you are assigning in the Page_Load
event overwrites the value you are setting in the button's OnClick
event. 根据页面生命周期 ,您在
Page_Load
事件中分配的selectedvalue会覆盖您在按钮的OnClick
事件中设置的值。 You should try to match the page lifecycle when assigning values to your controls. 在为控件分配值时,应尝试匹配页面生命周期。
In Page_Load, do a check if it's a postback request. 在Page_Load中,检查它是否是回发请求。 If it is, don't initialize your combo box.
如果是这样,请勿初始化您的组合框。
if (!IsPostback) {
cmbRequestState.SelectedValue = "2";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.