c# - SelectedValue 在 DropDownList 中回发时失败

标签 c# asp.net postback selectedvalue html-select

我最近在 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/

相关文章:

c# - BlazorInputFile - 不支持同步读取

c# - 在 C# 中比较 2 个价格作为数据类型字符串

ASP.Net session 在回发后偶尔会丢失

asp.net - 浏览器问题

ASP.Net:动态添加到占位符的用户控件无法检索值

c# - 创建处理多种事件类型的事件处理程序

c# - 在 Web 应用程序中使用 C# Windows 应用程序项目

javascript - 格式 $.ajax 调用 asp.net mvc

asp.net - 如何防止asp :Timer from sending tick before response is generated?

css - 页面回传上的 DotNetNuke CSS 问题?