简体   繁体   English

离开页面时记住级联下拉值

[英]Remember Cascading Dropdown value when navigating away from page

I maintain an application for my organization that uses Web Forms.我为我的组织维护一个使用 Web 窗体的应用程序。 I have to add cascading dropdowns and I need to have those dropdowns remember their values when I navigate away from the page.我必须添加级联下拉菜单,当我离开页面时,我需要让这些下拉菜单记住它们的值。 My first dropdown remembers its value but its cascading dropdown does not retain its value when I navigate back.我的第一个下拉菜单会记住它的值,但是当我返回时,它的级联下拉菜单不会保留它的值。 Any suggestions?有什么建议?

Below are my dropdowns:以下是我的下拉列表:

 <asp:UpdatePanel ID="updatePanel1" runat="server">
    <ContentTemplate><div class="dropDownSelection">
      <asp:DropDownList CssClass="topicDropDown" ID="topic1" DataTextField="NAME" DataValueField="ID" OnSelectedIndexChanged="Load_Section1" AutoPostBack="True" AppendDataBoundItems="true" runat="server"/>
      <asp:DropDownList CssClass="sectionDropDown" ID="section1" DataTextField="NAME" DataValueFile="ID" AutoPostBack="True" runat="server">
        <asp:ListItem Text="--- Select Section ---" Value="0"></asp:ListItem>
         </asp:DropDownList></div><br/>
    </ContentTemplate>
 </asp:UpdatePanel>

Below are the methods that load the dropdown values:以下是加载下拉值的方法:

protected void Load_Topic1()
    {
        var topicStore = new TopicStore();

        var topics = topicStore.ReadTopics();

        foreach (var topic in topics)
        {
            var topicListItem = new ListItem(topic.Name, topic.Id.ToString());
            topic1.Items.Add(topicListItem);
            //topic1.Attributes.Add("Title", topic.Description);//only shows description for item at the bottom of the dropdown
        }

        topic1.Items.Insert(0, new ListItem("--- Select Topic ---", "0"));
    }

    protected void Load_Section1(object sender, EventArgs e)
    {
        section1.Items.Clear();

        var sectionStore = new SectionStore();

        var sections = sectionStore.ReadForTopic(Guid.Parse(topic1.SelectedValue));

        foreach (var section in sections)
        {
            var sectionListItem = new ListItem(section.Name, section.Id.ToString());
            section1.Items.Add(sectionListItem);
        }

        section1.Items.Insert(0, new ListItem("--- Select Section ---", "0"));
    }

Load_Topic1 is called on page load. Load_Topic1 在页面加载时调用。 The values of the dropdowns are stored in session when you navigate away from the page.当您离开页面时,下拉列表的值存储在会话中。

Below is how I load the values into session:下面是我如何将值加载到会话中:

if (Session["Page"] != null)
{
    if (Session["SubmittedPayment"] != null)
    {
        //shazbot -- they've already hit submit
        Server.Transfer("default.aspx?logout=true");
    }
   topic1.SelectedValue = Session["topic1"] as string;
  section1.SelectedValue = Session["section1"] as string;
  rating1DropDown.SelectedValue = Session["rating1DropDown"] as string; 

    if (Session["Page"].ToString() == "HighSchoolInformation2.aspx")
    {
        Session.Add("Page", "InterestSurvey.aspx");
    }
    else if (Session["Page"].ToString() == "Payment.aspx" || Session["Page"].ToString() == "InterestSurvey.aspx")
    {
        Session.Add("Page", "InterestSurvey.aspx");
    }
  else 
  {
      topic1.SelectedValue = Session["topic1"] as string;
      section1.SelectedValue = Session["section1"] as string;
      rating1DropDown.SelectedValue = Session["rating1DropDown"] as string;
      Response.Redirect(Session["Page"].ToString());
   } 
}
   else
    {
    //they're not logged in, send them back to log in
    Server.Transfer("Default.aspx?logout=true");
    } 

In the code behind I load session variables like this:在后面的代码中,我像这样加载会话变量:

protected void next_Click(object sender, EventArgs e)
    {
        Session.Add("topic1", topic1.SelectedValue);
        Session.Add("section1", section1.SelectedValue);
        Session.Add("rating1DropDown", rating1DropDown.SelectedValue);

        Page.Validate();
        if (Page.IsValid)
        {
            ModLangRequired.Visible = false;

            if (!checkModLang())
            {
                Response.Redirect("Payment.aspx");
            }
        }
    }

Like I said up top I inherited this code and I don't have the time for a complete rewrite at the moment.就像我说的那样,我继承了这段代码,目前我没有时间完全重写。

Start by changing Load_Section1 as follows.首先按如下方式更改Load_Section1 Notice how we are using Guid.TryParse to conditionally load sections if a topic is selected.请注意我们如何使用Guid.TryParse在选择主题时有条件地加载部分。

protected void Load_Section1()
{
    section1.Items.Clear();

    section1.Items.Add(new ListItem("--- Select Section ---", "0"));

    Guid topicId;
    if (Guid.TryParse(topic1.SelectedValue, out topicId))
    {
        var sectionStore = new SectionStore();

        var sections = sectionStore.ReadForTopic(topicId);

        foreach (var section in sections)
        {
            var sectionListItem = new ListItem(section.Name, section.Id.ToString());
            section1.Items.Add(sectionListItem);
        }
    }
}

Then add a new event handler as follows:然后添加一个新的事件处理程序,如下所示:

protected void TopicDropDown_OnSelectedIndexChanged(object sender, EventArgs e)
{
    Load_Section1();
}

Now associate the OnSelectedIndexChanged event to the new handler:现在将OnSelectedIndexChanged事件关联到新的处理程序:

<asp:DropDownList ID="topic1" ... OnSelectedIndexChanged="TopicDropDown_OnSelectedIndexChanged" ... />

Now you can restore the the page state as follows:现在您可以按如下方式恢复页面状态:

if (Session["Page"] != null)
{
    if (Session["SubmittedPayment"] != null)
    {
        //shazbot -- they've already hit submit
        Server.Transfer("default.aspx?logout=true");
    }

    Load_Topic1();
    topic1.SelectedValue = IsPostBack ? Request.Form[topic1.UniqueID] : (string)Session["topic1"];
    Load_Section1();
    section1.SelectedValue = IsPostBack ? Request.Form[section1.UniqueID] : (string)Session["section1"];
    Load_Rating1DropDown(); // not sure if you need this???
    rating1DropDown.SelectedValue = IsPostBack ? Request.Form[rating1DropDown.UniqueID] : (string)Session["rating1DropDown"];   

    if (Session["Page"].ToString() == "HighSchoolInformation2.aspx")
    {
        Session.Add("Page", "InterestSurvey.aspx");
    }
    else if (Session["Page"].ToString() == "Payment.aspx" || Session["Page"].ToString() == "InterestSurvey.aspx")
    {
        Session.Add("Page", "InterestSurvey.aspx");
    }
    else 
    {
        // you don't actually need to set values before you redirect
        Response.Redirect(Session["Page"].ToString());
    } 
}
else
{
    //they're not logged in, send them back to log in
    Server.Transfer("Default.aspx?logout=true");
}

My assumption is the above code is called from Page_Load .我的假设是上面的代码是从Page_Load调用的。 Avoid making any extra calls to Load_Topic1 as well.避免对Load_Topic1进行任何额外调用。

Actually what's happening is, your cascade dropdown (section1) load it's items on the selection of topic1, and when page refresh, topic1 fetch it's value from managed ViewState and section1 renders blank...实际上发生的事情是,您的级联下拉列表(第 1 部分)在选择的主题 1 上加载它的项目,当页面刷新时,主题 1 从托管的 ViewState 中获取它的值,而第 1 部分呈现空白...

There are 2 solutions:有2种解决方案:

Manage it in script在脚本中管理它

Store section1's selectedValue in any storage like ViewState or localStorage (browser storage) and on document ready, you can fetch items for section1 against item selected in topic1 through ajax call and set the selected value which is stored in storage.将 section1 的 selectedValue 存储在 ViewState 或 localStorage(浏览器存储)等任何存储中,并且在文档准备就绪时,您可以通过 ajax 调用针对 topic1 中选择的项目获取 section1 的项目,并设置存储在存储中的选定值。 (Sounds much efforts, check below option) (听起来很努力,请检查以下选项)

Manage it in back-end code在后端代码中管理它

In your Page_Load method, call Load_Section1 and pass topic1.SelectedValue在您的 Page_Load 方法中,调用 Load_Section1 并传递 topic1.SelectedValue

Don't forget to put Page.IsPostBack condition to avoid error...不要忘记放置 Page.IsPostBack 条件以避免错误...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Xamarin 滑块:“值是最大值的无效值”(仅当导航离开页面时) - Xamarin Slider: 'Value is an invalid value for Maximum' (Only when navigating away from a page) 离开一页时如何清除会话 - How to clear Session when navigating away from one page 导航离开某个页面时执行c#命令 - Executing c# commands when navigating away from a certain page 从C#(.Net 3.5)页面导航时调用方法的方法? - Way to call a method when navigating away from a page in C# (.Net 3.5)? 如何在导航和返回页面时保留文本字段数据 - How to keep textfield data when navigating away and back to page 离开页面之前,将当前URL保存在控制器中 - Saving current url in controller before navigating away from page 在Silverlight中,将导航远离包含线程的页面结束线程吗? - In Silverlight, will navigating away from the page that contains a thread end the thread? 导航时记住匿名用户 - remember anonymous users when navigating 级联下拉菜单的默认值不起作用 - default value for cascading dropdown is not working UWP - 如果在async / await运行时离开页面会发生什么? - UWP - What happens if navigating away from page while async/await is running?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM