【问题标题】:Where are the DataValueField values for a CheckBoxList stored?CheckBoxList 的 DataValueField 值存储在哪里?
【发布时间】:2008-10-07 20:24:33
【问题描述】:

我在页面上有这个 CheckBoxList:

<asp:checkboxlist runat="server" id="Locations" datasourceid="LocationsDatasource"
   datatextfield="CountryName" datavaluefield="CountryCode" />

我想使用 Javascript 遍历客户端上的复选框元素并获取每个选中复选框的值,但这些值在客户端似乎不可用。 HTML 输出如下所示:

<table id="ctl00_Content_Locations" class="SearchFilterCheckboxlist" cellspacing="0" cellpadding="0" border="0" style="width:235px;border-collapse:collapse;">
<tr>
    <td><input id="ctl00_Content_Locations_0" type="checkbox" name="ctl00$Content$Locations$0" /><label for="ctl00_Content_Locations_0">Democratic Republic of the Congo</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_1" type="checkbox" name="ctl00$Content$Locations$1" /><label for="ctl00_Content_Locations_1">Central African Republic</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_2" type="checkbox" name="ctl00$Content$Locations$2" /><label for="ctl00_Content_Locations_2">Congo</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_3" type="checkbox" name="ctl00$Content$Locations$3" /><label for="ctl00_Content_Locations_3">Cameroon</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_4" type="checkbox" name="ctl00$Content$Locations$4" /><label for="ctl00_Content_Locations_4">Gabon</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_5" type="checkbox" name="ctl00$Content$Locations$5" /><label for="ctl00_Content_Locations_5">Equatorial Guinea</label></td>
</tr>

值(“cd”、“cg”、“ga”等)无处可寻。他们在哪?甚至可以在客户端访问它们,还是我需要使用中继器或其他东西自己构建此复选框列表?

【问题讨论】:

    标签: asp.net javascript


    【解决方案1】:

    我终于找到了我一直在寻找的答案!

    asp.net CheckboxList 控件确实实际上将 value 属性呈现为 HTML - 它已经在生产站点中为我工作了一年多! (我们总是为所有网站关闭 EnableViewState,它仍然可以正常工作,无需任何调整或黑客攻击)

    然而,突然有一天,它停止工作了,我们的 CheckboxList 复选框不再在 HTML 中呈现它们的 value 属性!你说什么?我们也是!解决这个问题需要一段时间,但由于它之前一直有效,我们知道必须有一个原因。原因是我们的 web.config 发生了意外更改!

    <pages controlRenderingCompatibilityVersion="3.5">
    

    我们从页面配置部分中删除了这个属性,这成功了!

    为什么会这样?我们反映了 CheckboxList 控件的代码,并在 RenderItem 方法中找到了这个:

    if (this.RenderingCompatibility >= VersionUtil.Framework40)
    {
        this._controlToRepeat.InputAttributes.Add("value", item.Value);
    }
    

    最亲爱的开发者兄弟姐妹们不要绝望!我在 Stackexchange 和其他网络上搜索的所有答案都提供了错误信息!从 .Net 4.0 开始,asp.net 呈现 CheckboxList 的复选框的 value 属性:

    <input type="checkbox" value="myvalue1" id="someid" />
    

    也许没有实际用处,Microsoft 让您能够将“controlRenderingCompatibilityVersion”添加到您的 web.config 以通过将版本设置为低于 4 来关闭它,这对于我们的目的来说是完全不必要的,实际上是有害的,因为javascript代码依赖于value属性...

    我们让所有复选框的 chk.val() 等于“on”,这是最初提醒我们注意这个问题的原因(使用 jquery.val() 获取复选框的值。转out "on" 是选中的复选框的值...每天学习一些东西)。

    【讨论】:

    • 请不要要求人们投票/接受您的答案。 Meta post regarding flagging such comments
    • 我知道这是一个非常老的问题,但我头上的头发被保存了。因为这个,我已经把头发扯掉了 4 个小时。由于这个微小的变化,一切正常。这是这个问题的最佳答案!
    • 删除 controlRenderingCompatibilityVersion 属性是否会对其他 .NET 组件产生任何副作用?
    • @EakanGopalakrishnan 见here。
    • 好像已经到4.0了,3.5的时候不行!
    【解决方案2】:
    <body>
         <form id="form1" runat="server">
              <div>
                   <asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="tx" DataValueField="vl">
                   </asp:CheckBoxList>
              </div>
              <input id="Button1" type="button" value="button" onclick="return Button1_onclick()" /> 
         </form>
    </body>
    <script type="text/javascript">
    
    function Button1_onclick() 
    {
    var itemarr = document.getElementById("CheckBoxList1").getElementsByTagName("span");
    var itemlen = itemarr.length;
         for(i = 0; i <itemlen;i++)
         {
              alert(itemarr[i].getAttribute("dvalue"));
         }
    return false;
    }
    
    
    </script>
    

    代码

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("tx");
            dt.Columns.Add("vl");
            DataRow dr = dt.NewRow();
            dr[0] = "asdas";
            dr[1] = "1";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "456456";
            dr[1] = "2";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "yjryut";
            dr[1] = "3";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "yjrfdgdfgyut";
            dr[1] = "3";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "34534";
            dr[1] = "3";
            dt.Rows.Add(dr);
            CheckBoxList1.DataSource = dt;
            CheckBoxList1.DataBind();
            foreach (ListItem li in CheckBoxList1.Items)
            {
                li.Attributes.Add("dvalue", li.Value);
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      存储在 ViewState 中,没有some hacking,您无法在客户端访问它们。

      【讨论】:

      • 谢谢。我想我只需要使用中继器构建复选框列表。
      【解决方案4】:

      为避免破坏复选框列表,只需使用中继器:

      <asp:Repeater ID="rptItems" runat="server" DataSourceID="odsDataSource">
      <ItemTemplate>
      <input id="iptCheckBox" type="checkbox" runat="server" value='<%# Eval("Key") %>'><%# Eval("Value") %></input>
      </ItemTemplate>
      </asp:Repeater>
      

      【讨论】:

        【解决方案5】:

        必须做一些非常讨厌的事情才能让它发挥作用..

                <asp:Repeater ID="rptItems" runat="server">
                    <ItemTemplate>
                        <input ID="iptCheckBox" type="checkbox" runat="server" value='<%# Eval("your_data_value") %>' />
                        <label ID="iptLabel" runat="server"><%# Eval("your_data_field") %></label>
                        <br />
                    </ItemTemplate>
                </asp:Repeater>
        

        代码隐藏:

        Private Sub rptItems_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptItems.ItemDataBound
            Dim checkBox As HtmlInputCheckBox = DirectCast(e.Item.FindControl("iptCheckBox"), HtmlInputCheckBox)
            Dim label As HtmlControl = DirectCast(e.Item.FindControl("iptLabel"), HtmlControl)
        
            label.Attributes.Add("for", checkBox.ClientID)
        End Sub
        

        【讨论】:

          【解决方案6】:

          Swapna,您的回答绝对有效。因此,为了检查 ASP.Net Checkboxlist 中的复选框是否被选中,然后将列表累积为逗号分隔的字符串,您可以这样做

          C# 代码隐藏

          ChkboxList1.DataSource = dsData;
          ChkboxList1.DataTextField = "your-display-column-name";
          ChkboxList1.DataValueField = "your-identifier-column-name";
          ChkboxList1.DataBind();
          
          foreach (ListItem li in ChkboxList1.Items)
          {
              li.Attributes.Add("DataValue", li.Value); 
          }
          

          然后在Javascript中做

          var selValues = "";
          var ChkboxList1Ctl = document.getElementById("ChkboxList1");
          var ChkboxList1Arr = null;
          var ChkboxList1Attr= null;
          
          if (ChkboxList1Ctl != null)
          {
             ChkboxList1Arr = ChkboxList1Ctl.getElementsByTagName("INPUT");
             ChkboxList1Attr = ChkboxList1Ctl.getElementByTagName("span");
          }
          if (ChkboxList1Arr != null)
          {
              for (var i = 0; i < ChkboxList1Arr.length; i++)
              {
                 if (ChkboxList1Arr[i].checked)
                     selValues += ChkboxList1Attr[i].getAttribute("DataValue") + ",";
              }
              if (selValues.length > 0)
                 selValues = selValues.substr(0, selValues.length - 1);
          }
          

          【讨论】:

            【解决方案7】:

            删除&lt;pages controlRenderingCompatibilityVersion="3.5"&gt; 导致我正在处理的一些旧代码出现问题。我收到this error。一旦我得到这个错误,我就意识到改变的风险太大了。

            为了解决这个问题,我最终扩展了 CheckBoxList 并覆盖了 Render 方法,为每个列表项添加了一个包含值的附加属性:

            public class CheckBoxListExt : CheckBoxList
            {
                protected override void Render(HtmlTextWriter writer)
                {
                    foreach (ListItem item in this.Items)
                    {
                        item.Attributes.Add("data-value", item.Value);
                    }
            
                    base.Render(writer);
                }
            }
            

            这将在外部span 标记上呈现data-value 属性。

            【讨论】:

              【解决方案8】:
              Easy Way I Do It.
              
              //First create query directly From Database that contains hidden field code format (i do it in stored procedure)
              
              SELECT Id,Name + '<input id="hf_Id" name="hf_Id" value="'+convert(nvarchar(100),Id)+'" type="hidden">' as Name FROM User
              
              //Then bind checkbox list as normally(i bind it from dataview).
              
              cbl.DataSource = dv;
              cbl.DataTextField = "Name";
              cbl.DataValueField = "Id";
              cbl.DataBind();
              
              //Then finally it represent code as follow.
              
              <table id="cbl_Position" border="0">
              <tbody>
              <tr>
              <td>
              <input id="cbl_0" name="cbl$0" type="checkbox">
              <label for="cbl_0">
              ABC
              <input id="hf_Id" name="hf_Id" value="1" type="hidden">
              </label>
              </td>
              </tr>
              </table>
              
              This way you can get DataValueField as inside hiddenfield and also can get it value from client side using javascript.
              

              【讨论】:

                【解决方案9】:

                我尝试了以下方法,它对我有用:

                <asp:CheckBoxList ID="chkAttachments" runat="server"></asp:CheckBoxList>
                

                服务器端绑定:

                private void LoadCheckBoxData()
                        {
                
                            var docList = new List<Documents>(); // need to get the list data from database
                                    chkAttachments.Items.Clear();
                
                                    ListItem item = new ListItem();
                                  
                                    foreach (var doc in docList )
                                    {
                                        item = new ListItem();
                                        item.Value = doc.Id.ToString();
                                        item.Text = doc.doc_name;
                                        chkAttachments.Items.Add(item);
                                    }
                                }
                    
                

                【讨论】:

                  猜你喜欢
                  • 2014-01-28
                  • 1970-01-01
                  • 2020-07-31
                  • 2018-11-09
                  • 1970-01-01
                  • 2018-06-04
                  • 2018-03-13
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多