简体   繁体   English

访问列表框项目在客户端添加

[英]Access list box items added on client side

  1. I have a listbox with runat=server 我有一个runat = server的列表框
    1. Items are added to this listbox on the client side, using javascript 使用javascript将项目添加到客户端的此列表框中
    2. I would want to retrieve the items on the server side on the click of a button 我想要点击一个按钮检索服务器端的项目

The problem is in the Buttons's server side click handler, I cannot see the new items added to the listbox. 问题出在Buttons的服务器端点击处理程序中,我看不到添加到列表框中的新项目。 Only the items that were there on page_load are displayed. 仅显示page_load上的项目。 How do i accomplish what i want to do 我如何完成我想做的事

Edit 1 编辑1

My Code Is like this 我的代码是这样的

 protected void Page_Load(object sender, EventArgs e)
    {


        if (!IsPostBack)
        {
            if (ViewState["gameID"] == null)
            {
                //Populate Listbox
                //Set gameid in viewstate
            }

            //Add javascript handlers to buttons
            btnSomeButton.Attributes.Add("onclick", "aJavaScriptFunction"); 

        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ListItemCollection x = ListBoxRanks.Items;
        //Here items is has just those items that are added to the listbox on page load

    }

Ah when abstractions leek :) 啊当抽象韭菜:)

Web server controls are serialised to view state before the response is sent, the control is recreated on postback and the options all put back from view state. Web服务器控件被序列化以在发送响应之前查看状态,在回发时重新创建控件,并且所有选项都从视图状态返回。

When you add option items client side they are not added to viewstate. 当您添加选项项客户端时,它们不会添加到viewstate。 The only way is to use your own hidden field to serialise client side additions and read them on postback or ajax the additions serverside. 唯一的方法是使用您自己的隐藏字段来序列化客户端添加并在回发时读取它们或者在服务器端添加ajax。

Only bind to the ListBox if Page.IsPostBack is false . 如果Page.IsPostBackfalse则仅绑定到ListBox。 This will allow you to see any items added on the client side. 这将允许您查看客户端添加的任何项目。

If you are binding to the control on each load you are wiping out any existing items that were loaded by ASP.NET from the request. 如果您在每个加载上绑定到控件,则会清除ASP.NET从请求中加载的所有现有项。 By only binding if the current page load was not triggered by a postback you are allowing all the items from the request to load, including any items added client-side. 通过仅绑定如果当前页面加载未被回发触发,您允许加载请求中的所有项目,包括客户端添加的任何项目。

You should use ajax to add items to the dropdown list. 您应该使用ajax将项添加到下拉列表中。 It will ensure your viewstate is in sync with the serverside dropdown control. 它将确保您的viewstate与服务器端下拉控件同步。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM