在哪里设置变量以使它们在回发时不为空?

问题描述 投票:0回答:1

我的网页允许用户从可用工具列表中选择一个或多个工具(通过从“可用”列表拖动到“选定”列表)。有一个

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();

在哪里可以设置工具变量,这样就不会出现“对象引用未设置”错误?

c# asp.net webforms postback
1个回答
2
投票

每个请求都由页面类的新实例处理,因此所有实例变量都会重置(正如您所发现的)。

您想要在请求中保留的值应存储在 ViewState(在 this 页面回发之间存储值)或 Session(在多个页面之间保存值)。

注意:不要将这些值存储在静态变量中。它们确实在回发之间保留其值,但也在所有访问者之间共享。

© www.soinside.com 2019 - 2024. All rights reserved.