gpt4 book ai didi

c# - 在 OnInit() 中获取控件值的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-30 21:22:26 26 4
gpt4 key购买 nike

我最近读了this article on smart use of ViewState并且我对 ViewState 中没有不必要的静态数据特别感兴趣。但是,我也很好奇我是否可以为父子下拉列表做同样的事情,比如经典的 Country/CountrySubDivision 示例。

所以我有这个标记:

    <asp:DropDownList runat="server" ID="ddlCountry" DataTextField="Name" DataValueField="ID" EnableViewState="false" />
<asp:DropDownList runat="server" ID="ddlCountrySubdivision" DataTextField="Name" DataValueField="ID" EnableViewState="false" />
<asp:Button runat="server" ID="btnTest" />

还有这个代码隐藏:

    public class Country
{
public string Name { get; set;}
public int Id { get; set; }
}

public class CountrySubdivision
{
public string Name { get; set; }
public int Id { get; set; }
public int CountryId { get; set; }
}

protected override void OnInit(EventArgs e)
{
var l = new List<Country>();
l.Add(new Country { Name = "A", Id = 1 });
l.Add(new Country { Name = "B", Id = 2 });
l.Add(new Country { Name = "C", Id = 3 });
ddlCountry.DataSource = l;
ddlCountry.DataBind();

var l2 = new List<CountrySubdivision>();
l2.Add(new CountrySubdivision { Name = "A1", Id = 1, CountryId = 1 });
l2.Add(new CountrySubdivision { Name = "A2", Id = 2, CountryId = 1 });
l2.Add(new CountrySubdivision { Name = "B1", Id = 4, CountryId = 2 });
l2.Add(new CountrySubdivision { Name = "B2", Id = 5, CountryId = 2 });
l2.Add(new CountrySubdivision { Name = "C1", Id = 7, CountryId = 3 });
l2.Add(new CountrySubdivision { Name = "C2", Id = 8, CountryId = 3 });

// this does not work: always comes out 1 regardless of what's actually selected
var selectedCountryId = string.IsNullOrEmpty(ddlCountry.SelectedValue) ? 1 : Int32.Parse(ddlCountry.SelectedValue);

// this does work:
var selectedCountryIdFromFormValues = Request.Form["ddlCountry"];

ddlCountrySubdivision.DataSource = l2.Where(x => x.CountryId == selectedCountryId).ToList();
ddlCountrySubdivision.DataBind();

base.OnInit(e);
}

所以我注意到的第一件事是,即使 EnableViewstatefalse,我的国家控件的值也会在请求中保持不变,无需额外的努力。甜的。这是很多序列化的东西,我不需要在提交表单时通过网络发送。

然后我用一对父子下拉菜单来到上面的示例,我看到 ddlCountry.SelectedValue 是默认值,而 Request.Form["ddlCountry"] 反射(reflect)了控件的值。

有没有一种方法可以保持 EnableViewState = "false" 而无需求助于 Request.Form 来获取依赖控件的值?

最佳答案

Then I came to the example above with a pair of parent-child drop downs, and I see that ddlCountry.SelectedValue is defaulting whereas Request.Form["ddlCountry"] is reflecting the control's value.

您看到此行为的原因是在页面生命周期的那个时刻,尚未加载 Viewstate。加载 Viewstate 时,它​​取自 Request.Form 对象值,因此您会在那里看到正确的值。

关于c# - 在 OnInit() 中获取控件值的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2320146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com