- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我最近在 ASP.NET DropDownList 中发现了一个奇怪的行为,我希望有人能解释一下。
基本上,我遇到的问题是在回发之前进行数据绑定(bind),然后将 SelectedValue
设置为数据项列表中不存在的值,调用根本没有效果。但是,在回发时,相同的调用将失败并出现 ArgumentOutOfRangeException()
'cmbCountry' 有一个无效的 SelectedValue,因为它不存在于项目列表中。参数名称:值
我正在使用以下代码。
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; }
}
有人可以为我澄清此行为的原因并建议是否有任何解决方法吗?
最佳答案
我不确定为什么要这样设计,但是 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;
}
}
您可以通过将 SelectedValue 设置为 null 而不是空字符串来解决此问题。
关于c# - SelectedValue 在 DropDownList 中回发时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11821549/
我有一个里面 在 GridView 中:
两个问题: 在回发时,当用户单击“提交”时,如何将错误消息添加到验证摘要中? 是否也可以使用内置的 .net 验证控件突出显示特定文本框? 最佳答案 动态创建 CustomValidator 控件并将
我的 Controller 用一个列表填充我的模型,该列表包含出现在我 View 中的 DropDownList 中的 strings。当 View 回发到我的 Controller 时,该列表突然为
我创建了两个输入框,并设置了 JavaScript,以便在达到最大长度时自动聚焦下一个框。它工作正常。但是当触发任何回发事件时,这些值变得清晰。我将 runat="server"放在输入框上,然后输入
我正在开发 asp.net 4.0(Web 表单),每当页面回发以验证凭据时,我都会在登录页面上遇到错误,它会显示以下错误。 Sys.WebForms.PageRequestManagerServer
我目前正在开发一个在 Sharepoint 中运行的 ASP.Net 网站。在解决问题之前,让我先给您一些背景信息。 我开发了 UserControl,然后将其添加为共享点页面上的 Web 部件。其中
我是一名优秀的程序员,十分优秀!