一位同事告诉我这件事:
他有一个DropDownList和一个网页上的按钮。这是背后的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem item = new ListItem("1");
item.Attributes.Add("title", "A");
ListItem item2 = new ListItem("2");
item2.Attributes.Add("title", "B");
DropDownList1.Items.AddRange(new[] {item, item2});
string s = DropDownList1.Items[0].Attributes["title"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
DropDownList1.Visible = !DropDownList1.Visible;
}
在页面加载时,项目的工具提示正在显示,但在第一次回发时,属性将丢失。为什么会这样,有没有解决办法?
答案 0 :(得分:69)
我遇到了同样的问题,想要贡献this资源,其中作者创建了一个继承的ListItem Consumer来将属性保存到ViewState。希望它会浪费我浪费的时间,直到我偶然发现它。
protected override object SaveViewState()
{
// create object array for Item count + 1
object[] allStates = new object[this.Items.Count + 1];
// the +1 is to hold the base info
object baseState = base.SaveViewState();
allStates[0] = baseState;
Int32 i = 1;
// now loop through and save each Style attribute for the List
foreach (ListItem li in this.Items)
{
Int32 j = 0;
string[][] attributes = new string[li.Attributes.Count][];
foreach (string attribute in li.Attributes.Keys)
{
attributes[j++] = new string[] {attribute, li.Attributes[attribute]};
}
allStates[i++] = attributes;
}
return allStates;
}
protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
object[] myState = (object[])savedState;
// restore base first
if (myState[0] != null)
base.LoadViewState(myState[0]);
Int32 i = 1;
foreach (ListItem li in this.Items)
{
// loop through and restore each style attribute
foreach (string[] attribute in (string[][])myState[i++])
{
li.Attributes[attribute[0]] = attribute[1];
}
}
}
}
答案 1 :(得分:35)
谢谢,拉勒米。正是我在寻找的东西。它完美地保持了属性。
要展开,下面是我使用Laramie的代码创建的类文件,用于在VS2008中创建下拉列表。在App_Code文件夹中创建类。创建类后,在aspx页面上使用此行进行注册:
<%@ Register TagPrefix="aspNewControls" Namespace="NewControls"%>
然后,您可以使用此
将控件放在您的网络表单上<aspNewControls:NewDropDownList ID="ddlWhatever" runat="server">
</aspNewControls:NewDropDownList>
好的,这是班级......
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Permissions;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NewControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class NewDropDownList : DropDownList
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
protected override object SaveViewState()
{
// create object array for Item count + 1
object[] allStates = new object[this.Items.Count + 1];
// the +1 is to hold the base info
object baseState = base.SaveViewState();
allStates[0] = baseState;
Int32 i = 1;
// now loop through and save each Style attribute for the List
foreach (ListItem li in this.Items)
{
Int32 j = 0;
string[][] attributes = new string[li.Attributes.Count][];
foreach (string attribute in li.Attributes.Keys)
{
attributes[j++] = new string[] { attribute, li.Attributes[attribute] };
}
allStates[i++] = attributes;
}
return allStates;
}
protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
object[] myState = (object[])savedState;
// restore base first
if (myState[0] != null)
base.LoadViewState(myState[0]);
Int32 i = 1;
foreach (ListItem li in this.Items)
{
// loop through and restore each style attribute
foreach (string[] attribute in (string[][])myState[i++])
{
li.Attributes[attribute[0]] = attribute[1];
}
}
}
}
}
}
答案 2 :(得分:13)
简单的解决方案是在下拉列表的pre-render
事件中添加工具提示属性。对状态的任何更改都应在pre-render
事件中完成。
示例代码:
protected void drpBrand_PreRender(object sender, EventArgs e)
{
foreach (ListItem _listItem in drpBrand.Items)
{
_listItem.Attributes.Add("title", _listItem.Text);
}
drpBrand.Attributes.Add("onmouseover", "this.title=this.options[this.selectedIndex].title");
}
答案 3 :(得分:8)
如果您只想在第一次加载页面时加载listitems,那么您需要启用ViewState,以便控件可以在那里序列化其状态并在页面回发时重新加载它。
有几个地方可以启用ViewState - 检查web.config中的<pages/>
节点以及{{1}的aspx文件本身顶部的<%@ page %>
指令属性。此设置需要EnableViewState
才能使ViewState正常工作。
如果您不想使用ViewState,只需从添加true
的代码周围删除if (!IsPostBack) { ... }
,并在每次回发时重新创建项目。
编辑:我道歉 - 我误解了你的问题。你是正确的属性没有在回发中存活,因为它们没有在ViewState中序列化。您必须在每次回发时重新添加这些属性。
答案 4 :(得分:6)
一个简单的解决方案 - 在请求回发的点击事件上调用您的下拉加载功能。
答案 5 :(得分:2)
此问题的典型解决方案涉及创建在正常情况下不太可行的新控件。对这个问题有一个简单而微不足道的解决方案。
问题是ListItem
在回发时失去了它的属性。但是,List本身永远不会丢失任何自定义属性。因此,可以以简单而有效的方式利用这一点。
步骤:
使用上面答案中的代码序列化您的属性(https://stackoverflow.com/a/3099755/3624833)
将其存储到ListControl的自定义属性(下拉列表,checklistbox等)。
在回发后,从ListControl读回自定义属性,然后将其反序列化为属性。
以下是我用来(de)序列化属性的代码(我需要做的是跟踪从后端检索时列表中最初呈现的选项,然后按照保存或删除行用户在UI上所做的更改:
string[] selections = new string[Users.Items.Count];
for(int i = 0; i < Users.Items.Count; i++)
{
selections[i] = string.Format("{0};{1}", Users.Items[i].Value, Users.Items[i].Selected);
}
Users.Attributes["data-item-previous-states"] = string.Join("|", selections);
(上面,&#34;用户&#34;是CheckboxList
控件)。
在回发后(在我的情况下是一个提交按钮点击事件),我使用下面的代码检索相同的内容并将它们存储到字典中进行后期处理:
Dictionary<Guid, bool> previousStates = new Dictionary<Guid, bool>();
string[] state = Users.Attributes["data-item-previous-states"].Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
foreach(string obj in state)
{
string[] kv = obj.Split(new char[] { ';' }, StringSplitOptions.None);
previousStates.Add(kv[0], kv[1]);
}
(PS:我有一个执行错误处理和数据转换的库函数,为简洁省略了相同的内容)。
答案 6 :(得分:1)
这是Laramie提出并由gleapman提炼的解决方案的VB.Net代码。
更新:我在下面发布的代码实际上是用于ListBox控件的。只需将继承更改为DropDownList并重命名该类。
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Security.Permissions
Imports System.Linq
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace CustomControls
<DefaultProperty("Text")> _
<ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")>
Public Class PersistentListBox
Inherits ListBox
<Bindable(True)> _
<Category("Appearance")> _
<DefaultValue("")> _
<Localizable(True)> _
Protected Overrides Function SaveViewState() As Object
' Create object array for Item count + 1
Dim allStates As Object() = New Object(Me.Items.Count + 1) {}
' The +1 is to hold the base info
Dim baseState As Object = MyBase.SaveViewState()
allStates(0) = baseState
Dim i As Int32 = 1
' Now loop through and save each attribute for the List
For Each li As ListItem In Me.Items
Dim j As Int32 = 0
Dim attributes As String()() = New String(li.Attributes.Count - 1)() {}
For Each attribute As String In li.Attributes.Keys
attributes(j) = New String() {attribute, li.Attributes(attribute)}
j += 1
Next
allStates(i) = attributes
i += 1
Next
Return allStates
End Function
Protected Overrides Sub LoadViewState(savedState As Object)
If savedState IsNot Nothing Then
Dim myState As Object() = DirectCast(savedState, Object())
' Restore base first
If myState(0) IsNot Nothing Then
MyBase.LoadViewState(myState(0))
End If
Dim i As Int32 = 1
For Each li As ListItem In Me.Items
' Loop through and restore each attribute
' NOTE: Ignore the first item as that is the base state and is represented by a Triplet struct
For Each attribute As String() In DirectCast(myState(i), String()())
li.Attributes(attribute(0)) = attribute(1)
i += 1
Next
Next
End If
End Sub
End Class
End Namespace
答案 7 :(得分:1)
@Sujay 您可以在下拉列表的值属性中添加以分号分隔的文本(如csv样式),并使用String.Split(&#39 ;;&#39;)获取2&#34;值&#34 ;超出一个值,作为一种解决方法,可以摆脱不必创建新的用户控件。特别是如果你只有很少的额外属性,如果它不是太长。您还可以在下拉列表的value属性中使用JSON值,然后从中解析出您需要的任何内容。
答案 8 :(得分:0)
//In the same block where the ddl is loaded (assuming the dataview is retrieved whether postback or not), search for the listitem and re-apply the attribute
if(IsPostBack)
foreach (DataRow dr in dvFacility.Table.Rows)
{
//search the listitem
ListItem li = ddl_FacilityFilter.Items.FindByValue(dr["FACILITY_CD"].ToString());
if (li!=null)
{
li.Attributes.Add("Title", dr["Facility_Description"].ToString());
}
} //end for each
答案 9 :(得分:0)
没有ViewState的简单解决方案,创建新的服务器控件或smth complex:
创建:
public void AddItemList(DropDownList list, string text, string value, string group = null, string type = null)
{
var item = new ListItem(text, value);
if (!string.IsNullOrEmpty(group))
{
if (string.IsNullOrEmpty(type)) type = "group";
item.Attributes["data-" + type] = group;
}
list.Items.Add(item);
}
更新
public void ChangeItemList(DropDownList list, string eq, string group = null, string type = null)
{
var listItem = list.Items.Cast<ListItem>().First(item => item.Value == eq);
if (!string.IsNullOrEmpty(group))
{
if (string.IsNullOrEmpty(type)) type = "group";
listItem.Attributes["data-" + type] = group;
}
}
示例:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (var context = new WOContext())
{
context.Report_Types.ToList().ForEach(types => AddItemList(DropDownList1, types.Name, types.ID.ToString(), types.ReportBaseTypes.Name));
DropDownList1.DataBind();
}
}
else
{
using (var context = new WOContext())
{
context.Report_Types.ToList().ForEach(types => ChangeItemList(DropDownList1, types.ID.ToString(), types.ReportBaseTypes.Name));
}
}
}
答案 10 :(得分:0)
我设法使用Session Variables实现了这一点,在我的情况下,我的列表不会包含很多元素,所以它的工作原理非常好,这就是我做到的:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] elems;//Array with values to add to the list
for (int q = 0; q < elems.Length; q++)
{
ListItem li = new ListItem() { Value = "text", Text = "text" };
li.Attributes["data-image"] = elems[q];
myList.Items.Add(li);
HttpContext.Current.Session.Add("attr" + q, elems[q]);
}
}
else
{
for (int o = 0; o < webmenu.Items.Count; o++)
{
myList.Items[o].Attributes["data-image"] = HttpContext.Current.Session["attr" + o].ToString();
}
}
}
当第一次加载页面时,填充列表并添加一个在回发后丢失的Image属性:(所以当我添加具有其属性的元素时,我创建一个Session变量“attr”加上数量取自“for”循环的元素(它将像attr0,attr1,attr2等......)并在其中我保存属性的值(在我的情况下是图像的路径),当发生回发时(在“else”中我只是循环列表并使用“for”循环的“int”添加从Session变量中获取的属性,该循环与页面加载时相同(这是因为在此页面中我做了没有添加元素到列表只是选择所以他们总是相同的索引)和属性再次设置,我希望这有助于将来的人,问候!