ASP .NET 2.0 and JavaScript / JS - Select Options disappear

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?UmljaGFyZA==?=

    ASP .NET 2.0 and JavaScript / JS - Select Options disappear

    Hi,

    I have an ASP .NET page with codebehind in a vb file.
    The page has a dropdown control, and a JS function which used HTTP XML
    Request to get the data from the database, and populate the dropdown.
    Actually, the JS creates the OPTION elements using th retrieved db data, and
    adds them to the SELECT element using DOM objects.

    The dropdown works ok, and the items are visible, but when the user clicks
    "Save" button, and the page posts back to the server, in the VB codebehind,
    the selected value in the dropdown is empty, and the items collection is
    empty.

    Why is this? How can I fix this behavior?

    Thanks in advance,

    Richard
  • wisccal@googlemail.com

    #2
    Re: ASP .NET 2.0 and Javascript / JS - Select Options disappear

    Hi Richard,

    The problem is that ASP maintains state by using ViewState. When you
    post back a page, controls are first instantiated, then initialized
    with values from ViewState, and at the very end, the SaveViewState
    event is called. The next time you post back, the values that were
    saved in the SaveViewState event will again be used to repopulate the
    controls on Initialization.

    When you modify controls like Dropdowns through Javascript (modify as
    in add members, not changing the selected index), the server cannot
    possibly know about this.

    In your case, I would suggest you use the internal __doPostBack
    Javscript function. You can check out the source of any aspx page in
    your browser, and will find it there:

    function __doPostBack(ev entTarget, eventArgument) {
    ....
    }

    You also need your page to implement IPostBackEventH andler to handle
    the async postback. An example follows:

    aspx page:

    <%@ Page Language="C#" AutoEventWireup ="True"
    CodeBehind="Def ault.aspx.cs"
    Inherits="Imple mentIPostBackEv entHandler._Def ault"
    EnableViewState ="false" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
    www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
    <title>Untitl ed Page</title>
    </head>
    <body>
    <script>
    function populateListBox () {
    var lst = document.getEle mentById('theLi stBox');
    var postBackArg = new Array()
    for(var i = 1;i <= 3;i++) {
    var newOptionName = "element_" + i;
    var newOptionValue = i;
    var newOption = new Option(newOptio nName,
    newOptionValue) ;
    lst.options.add (newOption);
    postBackArg[i-1] = newOptionName + "," +
    newOptionValue;
    }
    __doPostBack('< %= this.ClientID %>',
    postBackArg.joi n(";"));
    }
    </script>
    <form id="form1" runat="server">
    <div>
    <asp:ListBox ID="theListBox " runat="server" />
    <input id="btnTriggerJ s" type="button" value="btnTrigg erJs"
    OnClick="popula teListBox()" />
    <asp:Button ID="btnPostBack " OnClick="btnPos tBack_Click"
    Text="btnPostBa ck" runat="server" />
    </div>
    </form>
    </body>
    </html>


    codebehind file:
    using System;
    using System.Collecti ons;
    using System.Web.UI;
    using System.Web.UI.W ebControls;

    namespace ImplementIPostB ackEventHandler
    {
    public partial class _Default : System.Web.UI.P age,
    IPostBackEventH andler
    {
    protected void Page_Load(objec t sender, EventArgs e)
    {
    }

    protected void btnPostBack_Cli ck(object sender, EventArgs e)
    {
    foreach(ListIte m li in theListBox.Item s)
    {
    /* ... */
    }
    }

    public void RaisePostBackEv ent(string eventArg)
    {
    string[] newElements = eventArg.Split( ';');
    foreach(string newElement in newElements)
    {
    string[] newElementArray = newElement.Spli t(',');
    theListBox.Item s.Add(new ListItem(newEle mentArray[0],
    newElementArray[1]));
    }
    }
    }
    }

    =============== =
    Regards,
    Steve


    Richard wrote:
    Hi,
    >
    I have an ASP .NET page with codebehind in a vb file.
    The page has a dropdown control, and a JS function which used HTTP XML
    Request to get the data from the database, and populate the dropdown.
    Actually, the JS creates the OPTION elements using th retrieved db data, and
    adds them to the SELECT element using DOM objects.
    >
    The dropdown works ok, and the items are visible, but when the user clicks
    "Save" button, and the page posts back to the server, in the VB codebehind,
    the selected value in the dropdown is empty, and the items collection is
    empty.
    >
    Why is this? How can I fix this behavior?
    >
    Thanks in advance,
    >
    Richard

    Comment

    • =?Utf-8?B?UmljaGFyZA==?=

      #3
      Re: ASP .NET 2.0 and Javascript / JS - Select Options disappear

      Thanks Steve, great explanation.
      It'd be nice in JS to have a function to add objects to the viewstate ;-)

      As I'm using vb in the codebehind, is it necessary to have in the code
      behind page in its own namespace with the following code you posted?

      namespace ImplementIPostB ackEventHandler
      {
      ....
      }

      Thanks in advance,

      Richard

      "wisccal@google mail.com" wrote:
      Hi Richard,
      >
      The problem is that ASP maintains state by using ViewState. When you
      post back a page, controls are first instantiated, then initialized
      with values from ViewState, and at the very end, the SaveViewState
      event is called. The next time you post back, the values that were
      saved in the SaveViewState event will again be used to repopulate the
      controls on Initialization.
      >
      When you modify controls like Dropdowns through Javascript (modify as
      in add members, not changing the selected index), the server cannot
      possibly know about this.
      >
      In your case, I would suggest you use the internal __doPostBack
      Javscript function. You can check out the source of any aspx page in
      your browser, and will find it there:
      >
      function __doPostBack(ev entTarget, eventArgument) {
      ....
      }
      >
      You also need your page to implement IPostBackEventH andler to handle
      the async postback. An example follows:
      >
      aspx page:
      >
      <%@ Page Language="C#" AutoEventWireup ="True"
      CodeBehind="Def ault.aspx.cs"
      Inherits="Imple mentIPostBackEv entHandler._Def ault"
      EnableViewState ="false" %>
      >
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
      www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
      >
      <html xmlns="http://www.w3.org/1999/xhtml" >
      <head runat="server">
      <title>Untitl ed Page</title>
      </head>
      <body>
      <script>
      function populateListBox () {
      var lst = document.getEle mentById('theLi stBox');
      var postBackArg = new Array()
      for(var i = 1;i <= 3;i++) {
      var newOptionName = "element_" + i;
      var newOptionValue = i;
      var newOption = new Option(newOptio nName,
      newOptionValue) ;
      lst.options.add (newOption);
      postBackArg[i-1] = newOptionName + "," +
      newOptionValue;
      }
      __doPostBack('< %= this.ClientID %>',
      postBackArg.joi n(";"));
      }
      </script>
      <form id="form1" runat="server">
      <div>
      <asp:ListBox ID="theListBox " runat="server" />
      <input id="btnTriggerJ s" type="button" value="btnTrigg erJs"
      OnClick="popula teListBox()" />
      <asp:Button ID="btnPostBack " OnClick="btnPos tBack_Click"
      Text="btnPostBa ck" runat="server" />
      </div>
      </form>
      </body>
      </html>
      >
      >
      codebehind file:
      using System;
      using System.Collecti ons;
      using System.Web.UI;
      using System.Web.UI.W ebControls;
      >
      namespace ImplementIPostB ackEventHandler
      {
      public partial class _Default : System.Web.UI.P age,
      IPostBackEventH andler
      {
      protected void Page_Load(objec t sender, EventArgs e)
      {
      }
      >
      protected void btnPostBack_Cli ck(object sender, EventArgs e)
      {
      foreach(ListIte m li in theListBox.Item s)
      {
      /* ... */
      }
      }
      >
      public void RaisePostBackEv ent(string eventArg)
      {
      string[] newElements = eventArg.Split( ';');
      foreach(string newElement in newElements)
      {
      string[] newElementArray = newElement.Spli t(',');
      theListBox.Item s.Add(new ListItem(newEle mentArray[0],
      newElementArray[1]));
      }
      }
      }
      }
      >
      =============== =
      Regards,
      Steve

      >
      Richard wrote:
      Hi,

      I have an ASP .NET page with codebehind in a vb file.
      The page has a dropdown control, and a JS function which used HTTP XML
      Request to get the data from the database, and populate the dropdown.
      Actually, the JS creates the OPTION elements using th retrieved db data, and
      adds them to the SELECT element using DOM objects.

      The dropdown works ok, and the items are visible, but when the user clicks
      "Save" button, and the page posts back to the server, in the VB codebehind,
      the selected value in the dropdown is empty, and the items collection is
      empty.

      Why is this? How can I fix this behavior?

      Thanks in advance,

      Richard
      >

      Comment

      • wisccal@googlemail.com

        #4
        Re: ASP .NET 2.0 and Javascript / JS - Select Options disappear

        Hi Richard,

        No, the namespace was automatically generated by VS. No need for it.
        Just make sure that the Inherits directive in the aspx file will not
        have a namespace either (eg, Inherits="_Defa ult" instead of
        Inherits="Imple mentIPostBackEv entHandler._Def ault")

        ===========
        Regards,
        Steve


        Richard wrote:
        Thanks Steve, great explanation.
        It'd be nice in JS to have a function to add objects to the viewstate ;-)
        >
        As I'm using vb in the codebehind, is it necessary to have in the code
        behind page in its own namespace with the following code you posted?
        >
        namespace ImplementIPostB ackEventHandler
        {
        ...
        }
        >
        Thanks in advance,
        >
        Richard
        >
        "wisccal@google mail.com" wrote:
        >
        Hi Richard,

        The problem is that ASP maintains state by using ViewState. When you
        post back a page, controls are first instantiated, then initialized
        with values from ViewState, and at the very end, the SaveViewState
        event is called. The next time you post back, the values that were
        saved in the SaveViewState event will again be used to repopulate the
        controls on Initialization.

        When you modify controls like Dropdowns through Javascript (modify as
        in add members, not changing the selected index), the server cannot
        possibly know about this.

        In your case, I would suggest you use the internal __doPostBack
        Javscript function. You can check out the source of any aspx page in
        your browser, and will find it there:

        function __doPostBack(ev entTarget, eventArgument) {
        ....
        }

        You also need your page to implement IPostBackEventH andler to handle
        the async postback. An example follows:

        aspx page:

        <%@ Page Language="C#" AutoEventWireup ="True"
        CodeBehind="Def ault.aspx.cs"
        Inherits="Imple mentIPostBackEv entHandler._Def ault"
        EnableViewState ="false" %>

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
        www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

        <html xmlns="http://www.w3.org/1999/xhtml" >
        <head runat="server">
        <title>Untitl ed Page</title>
        </head>
        <body>
        <script>
        function populateListBox () {
        var lst = document.getEle mentById('theLi stBox');
        var postBackArg = new Array()
        for(var i = 1;i <= 3;i++) {
        var newOptionName = "element_" + i;
        var newOptionValue = i;
        var newOption = new Option(newOptio nName,
        newOptionValue) ;
        lst.options.add (newOption);
        postBackArg[i-1] = newOptionName + "," +
        newOptionValue;
        }
        __doPostBack('< %= this.ClientID %>',
        postBackArg.joi n(";"));
        }
        </script>
        <form id="form1" runat="server">
        <div>
        <asp:ListBox ID="theListBox " runat="server" />
        <input id="btnTriggerJ s" type="button" value="btnTrigg erJs"
        OnClick="popula teListBox()" />
        <asp:Button ID="btnPostBack " OnClick="btnPos tBack_Click"
        Text="btnPostBa ck" runat="server" />
        </div>
        </form>
        </body>
        </html>


        codebehind file:
        using System;
        using System.Collecti ons;
        using System.Web.UI;
        using System.Web.UI.W ebControls;

        namespace ImplementIPostB ackEventHandler
        {
        public partial class _Default : System.Web.UI.P age,
        IPostBackEventH andler
        {
        protected void Page_Load(objec t sender, EventArgs e)
        {
        }

        protected void btnPostBack_Cli ck(object sender, EventArgs e)
        {
        foreach(ListIte m li in theListBox.Item s)
        {
        /* ... */
        }
        }

        public void RaisePostBackEv ent(string eventArg)
        {
        string[] newElements = eventArg.Split( ';');
        foreach(string newElement in newElements)
        {
        string[] newElementArray = newElement.Spli t(',');
        theListBox.Item s.Add(new ListItem(newEle mentArray[0],
        newElementArray[1]));
        }
        }
        }
        }

        =============== =
        Regards,
        Steve


        Richard wrote:
        Hi,
        >
        I have an ASP .NET page with codebehind in a vb file.
        The page has a dropdown control, and a JS function which used HTTP XML
        Request to get the data from the database, and populate the dropdown.
        Actually, the JS creates the OPTION elements using th retrieved db data, and
        adds them to the SELECT element using DOM objects.
        >
        The dropdown works ok, and the items are visible, but when the user clicks
        "Save" button, and the page posts back to the server, in the VB codebehind,
        the selected value in the dropdown is empty, and the items collection is
        empty.
        >
        Why is this? How can I fix this behavior?
        >
        Thanks in advance,
        >
        Richard

        Comment

        • =?Utf-8?B?UmljaGFyZA==?=

          #5
          Re: ASP .NET 2.0 and Javascript / JS - Select Options disappear

          Hello,

          Steve, I really appreciate your help with this, and I know this example is a
          very sophisticated code.

          Now, somehow sending data in strings around, seems like the only solution in
          Web applications!?? , but it doesn't seem like a very good practice.

          1) A dropdown could have many items with fairly long descriptions. If the
          resulting string overflows the string size, we'd end up with a truncated
          dropdown or an invalid string that cannot be parsed back into a dropdown.

          2) With a string, its's hard to store state like "disabled" and other
          members of the dropdown.

          Seriously , isn't there a "best practice" kindof way of doing this?

          Thanks in advance,

          Richard
          =====
          "wisccal@google mail.com" wrote:
          Hi Richard,
          >
          No, the namespace was automatically generated by VS. No need for it.
          Just make sure that the Inherits directive in the aspx file will not
          have a namespace either (eg, Inherits="_Defa ult" instead of
          Inherits="Imple mentIPostBackEv entHandler._Def ault")
          >
          ===========
          Regards,
          Steve

          >
          Richard wrote:
          Thanks Steve, great explanation.
          It'd be nice in JS to have a function to add objects to the viewstate ;-)

          As I'm using vb in the codebehind, is it necessary to have in the code
          behind page in its own namespace with the following code you posted?

          namespace ImplementIPostB ackEventHandler
          {
          ...
          }

          Thanks in advance,

          Richard

          "wisccal@google mail.com" wrote:
          Hi Richard,
          >
          The problem is that ASP maintains state by using ViewState. When you
          post back a page, controls are first instantiated, then initialized
          with values from ViewState, and at the very end, the SaveViewState
          event is called. The next time you post back, the values that were
          saved in the SaveViewState event will again be used to repopulate the
          controls on Initialization.
          >
          When you modify controls like Dropdowns through Javascript (modify as
          in add members, not changing the selected index), the server cannot
          possibly know about this.
          >
          In your case, I would suggest you use the internal __doPostBack
          Javscript function. You can check out the source of any aspx page in
          your browser, and will find it there:
          >
          function __doPostBack(ev entTarget, eventArgument) {
          ....
          }
          >
          You also need your page to implement IPostBackEventH andler to handle
          the async postback. An example follows:
          >
          aspx page:
          >
          <%@ Page Language="C#" AutoEventWireup ="True"
          CodeBehind="Def ault.aspx.cs"
          Inherits="Imple mentIPostBackEv entHandler._Def ault"
          EnableViewState ="false" %>
          >
          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
          www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
          >
          <html xmlns="http://www.w3.org/1999/xhtml" >
          <head runat="server">
          <title>Untitl ed Page</title>
          </head>
          <body>
          <script>
          function populateListBox () {
          var lst = document.getEle mentById('theLi stBox');
          var postBackArg = new Array()
          for(var i = 1;i <= 3;i++) {
          var newOptionName = "element_" + i;
          var newOptionValue = i;
          var newOption = new Option(newOptio nName,
          newOptionValue) ;
          lst.options.add (newOption);
          postBackArg[i-1] = newOptionName + "," +
          newOptionValue;
          }
          __doPostBack('< %= this.ClientID %>',
          postBackArg.joi n(";"));
          }
          </script>
          <form id="form1" runat="server">
          <div>
          <asp:ListBox ID="theListBox " runat="server" />
          <input id="btnTriggerJ s" type="button" value="btnTrigg erJs"
          OnClick="popula teListBox()" />
          <asp:Button ID="btnPostBack " OnClick="btnPos tBack_Click"
          Text="btnPostBa ck" runat="server" />
          </div>
          </form>
          </body>
          </html>
          >
          >
          codebehind file:
          using System;
          using System.Collecti ons;
          using System.Web.UI;
          using System.Web.UI.W ebControls;
          >
          namespace ImplementIPostB ackEventHandler
          {
          public partial class _Default : System.Web.UI.P age,
          IPostBackEventH andler
          {
          protected void Page_Load(objec t sender, EventArgs e)
          {
          }
          >
          protected void btnPostBack_Cli ck(object sender, EventArgs e)
          {
          foreach(ListIte m li in theListBox.Item s)
          {
          /* ... */
          }
          }
          >
          public void RaisePostBackEv ent(string eventArg)
          {
          string[] newElements = eventArg.Split( ';');
          foreach(string newElement in newElements)
          {
          string[] newElementArray = newElement.Spli t(',');
          theListBox.Item s.Add(new ListItem(newEle mentArray[0],
          newElementArray[1]));
          }
          }
          }
          }
          >
          =============== =
          Regards,
          Steve

          >
          Richard wrote:
          Hi,

          I have an ASP .NET page with codebehind in a vb file.
          The page has a dropdown control, and a JS function which used HTTP XML
          Request to get the data from the database, and populate the dropdown.
          Actually, the JS creates the OPTION elements using th retrieved db data, and
          adds them to the SELECT element using DOM objects.

          The dropdown works ok, and the items are visible, but when the user clicks
          "Save" button, and the page posts back to the server, in the VB codebehind,
          the selected value in the dropdown is empty, and the items collection is
          empty.

          Why is this? How can I fix this behavior?

          Thanks in advance,

          Richard
          >
          >

          Comment

          Working...