TheMonkeyMan TheMonkeyMan - 1 month ago 8
ASP.NET (C#) Question

ASP:ListItem store object

I have an

<asp:ListItem>
control and I am looking to extend this to have 2 values. Can someone help me to do this.

Basically I want
<asp:ListItem value="x" value2="b" text="Hello">


Does anyone know how I can accomplish this. I thought about creating an object and storing it in the value filed with the appropriate .ToString() Method however I can only store strings in list items.

If I created this in HTML I could just throw an attribute and read them but I create my list items in the code behind so I am unsure of how to add an attribute.

Update

One way is to use 'data-' that is used in HTML5. But for two way data over-ride the control to add the additional value so that the ViewState caches it.

AVD AVD
Answer

If your requirement is to use value attribute by client-script then I'd suggest to store jsonString. Here is a workaround.

<asp:ListItem value="{'d': ['x','b'] }" text="Hello">

Sample:

Product.cs

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Desc { get; set; }
    public string JsonString
    {
        get
        {
            return "{\"d\": [\"" + ID + "\",\"" + Desc + "\"]}";
        }
    }
}

Binding the List<T>

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<Product> products = new List<Product>()
        {
             new Product(){ ID=1, Name="A", Desc="A1"},
             new Product(){ ID=2, Name="B", Desc="B1"},
             new Product(){ ID=3, Name="C", Desc="C1"},
        };

        ListBox1.DataSource = products;
        ListBox1.DataTextField = "Name";
        ListBox1.DataValueField = "JsonString";
        ListBox1.DataBind();
    }
}

Markup

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#ListBox1").change(function () {
                var sel = $(this).val();
                v = jQuery.parseJSON(sel);
                console.log(v.d[0] + " " + v.d[1]);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
    </div>
</body>