我的网页允许用户从可用工具列表中选择一个或多个工具(通过从“可用”列表拖动到“选定”列表)。有一个
HiddenTools
隐藏字段,每次两个列表更改时都会更新 - <li>
列表中的 ToolsActive
存储为 HiddenTools
中以逗号分隔的 ID 列表。当用户单击“保存”时,HiddenTools
中的值将存储在数据库中。
aspx 页面:
<asp:HiddenField runat="server" ID="HiddenTools"/>
/*<li> can be dragged from one list to the other. Every time the lists
change, HiddenTools gets updated with the contents of ToolsSelected
list, formatted as a comma separated string */
<ul id="ToolsAvailable">
<%foreach (KeyValuePair<int,string> tool in unusedTools){ %>
<li id='<%= tool.Key %>'> <%= tool.Value %> </li>
<% } %>
</ul>
<ul id="ToolsActive">
<%foreach (KeyValuePair<int,string> aTool in selectedTools){ %>
<li id='<%= aTool.Key %>'> <%= tool.Value %> </li>
<% } %>
</ul>
<asp:Button ID="btnSave" OnClick="btnSave_Click" runat="server" Text="Save"/>
隐藏代码:
public partial class Settings
{
protected ToolPreferences prefs;
protected Dictionary<int, string> tools;
protected Dictionary<int, string> unusedTools;
protected Dictionary<int, string> selectedTools;
protected void Page_Load(object sender, EventArgs e)
{
int AccountId = getAccountId();
if(!Page.IsPostBack){
prefs = new ToolPreferences(AccountId);
PopulateTools();
}
}
private void PopulateTools()
{
tools = getPossibleTools();
unusedTools = new Dictionary<int, string>();
selectedTools = new Dictionary<int, string>();
List<int> selectedList = new List<int>();
if (!string.IsNullOrEmpty(prefs.Tools))
{
selectedList = prefs.Tools.Split(',').Select(int.Parse).ToList();
}
foreach (KeyValuePair<int, string> aTool in tools)
{
if (selectedList.Contains(aTool.Key))
{
selectedTools.Add(aTool.Key, aTool.Value);
}
else
{
unusedTools.Add(aTool.Key, aTool.Value);
}
}
}
protected void btnSavePreferences_Click(object sender, EventArgs e)
{
ToolPreferences tp = ToolPreferences (AccountId);
tp.Update(HiddenTools.Value);
}
}
问题是PostBack后,出现以下错误:
未将对象引用设置为对象的实例。
突出显示以下行:
<%foreach (KeyValuePair<int,string> tool in unusedTools){ %>
如果我将以下两行移出
!PageIsPostBack
检查,则回发后重新加载页面时我不会收到该错误,但在页面重新加载之前我也看不到用户对工具列表所做的更改再次重新加载。
prefs = new ToolPreferences(AccountId);
PopulateTools();
在哪里可以设置工具变量,这样就不会出现“对象引用未设置”错误?