asp.net 在哪里设置变量,使它们在回发时不为null?

zqdjd7g9  于 5个月前  发布在  .NET
关注(0)|答案(1)|浏览(76)

我的网页允许用户从可用工具列表中选择一个或多个工具(通过从“可用”列表拖动到“选定”列表)。有一个HiddenTools隐藏字段,每当两个列表改变时都会更新-ToolsActive列表中的<li>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);
    }        

}


问题是在回发后,出现以下错误:
Object reference not set to an instance of an object.
并突出显示以下行:
<%foreach (KeyValuePair<int,string> tool in unusedTools){ %>
如果我将下面两行移出!PageIsPostBack检查,当页面在回发后重新加载时,我不会得到该错误,但我也看不到用户对工具列表所做的更改,直到页面再次重新加载。

prefs = new ToolPreferences(AccountId);
PopulateTools();

在哪里可以设置工具变量,以避免出现“Object reference not set”错误?

x759pob2

x759pob21#

每个请求都由页面类的一个新示例处理,因此所有示例变量都被重置(正如您所发现的)。
您希望在请求中保留的值应该存储在ViewState(在 this 页面中存储回发之间的值)或Session(在多个页面之间保存值)中。
注意:不要将这些值存储在静态变量中。它们在回发之间保留它们的值,但也在所有访问者之间共享。

相关问题