最近,我读this article on smart use of ViewState和我在ViewState中没有不必要的静态数据特别感兴趣。不过,我也很好奇,如果我可以为父母 - 子女下拉菜单做同样的事情,就像经典的Country/CountrySubDivision示例一样。什么是在OnInit()中获取控件值的最佳方法?
所以我有这个标记:
<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);
}
所以我首先注意到的是,即使EnableViewstate
为false
,我国控件的值不同请求间保留没有额外的努力。甜。这是很多序列化的东西,我不需要通过表单提交发送。
然后我用一对父母子女下拉菜单来看上面的例子,我看到ddlCountry.SelectedValue
是默认的,而Request.Form["ddlCountry"]
正反映了控件的价值。
有没有办法保持EnableViewState = "false"
而不求助于Request.Form
来获得依赖控件的值?
呀,问题是,我不希望通过线路发送的每一个回发200个国家的一大旧列表,因为它真的没有必要。我们目前使用EnableViewState =“true”并在OnLoad中执行操作。 – 2010-02-23 17:26:19
@Josh - 为什么不使用pagemethod呢?你可以传回选定的值,然后你的依赖选择列表可以使用该值来填充自己。可能意味着你需要改变你的方法,但是这种方式的东西越少越好。 – nickytonline 2010-02-23 18:19:56