Max*_*ich 6 c# asp.net postback html-select selectedvalue
我最近在ASP.NET DropDownList中发现了一个奇怪的行为,我希望有人可以解释一下.
基本上我遇到的问题是在回发之前进行数据绑定,然后将数据项设置为数据项SelectedValue
列表中不存在的值时,调用根本没有效果.但是在回发时,同一个呼叫将失败ArgumentOutOfRangeException()
'cmbCountry'有一个SelectedValue,它是无效的,因为它在项目列表中不存在.参数名称:value
我正在使用以下代码.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cmbCountry.DataSource = GetCountries();
cmbCountry.DataBind();
cmbCountry.SelectedValue = ""; //No effect
}
else
{
cmbCountry.SelectedValue = ""; //ArgumentOutOfRangeException is thrown
}
}
protected List<Country> GetCountries()
{
List<Country> result = new List<Country>();
result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test" });
result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test1" });
result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test2" });
result.Add(new Country() { ID = Guid.NewGuid(), Description = "Test3" });
return result;
}
public class Country
{
public Country() { }
public Guid ID { get; set; }
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
有人可以请我澄清这种行为的原因,并建议是否有任何解决方法?
我不知道为什么它是这样设计的,但 DropDownList 只在 PostBack 上抛出这个异常...这是来自 ILSpy 的 setter 代码:
public virtual string SelectedValue
{
get { ... }
set
{
if (this.Items.Count != 0)
{
if (value == null || (base.DesignMode && value.Length == 0))
{
this.ClearSelection();
return;
}
ListItem listItem = this.Items.FindByValue(value);
/********** Checks IsPostBack here **********/
bool flag = this.Page != null &&
this.Page.IsPostBack &&
this._stateLoaded;
if (flag && listItem == null)
{
throw new ArgumentOutOfRangeException("value",
SR.GetString("ListControl_SelectionOutOfRange", new object[]
{
this.ID,
"SelectedValue"
}));
}
if (listItem != null)
{
this.ClearSelection();
listItem.Selected = true;
}
}
this.cachedSelectedValue = value;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过将 SelectedValue 设置为 null 而不是空字符串来解决此问题。
归档时间: |
|
查看次数: |
2773 次 |
最近记录: |