Binding data to html5 DataList in asp.net

µMax picture µMax · Mar 26, 2013 · Viewed 7.2k times · Source

I'm trying my hands with HTML5. Is it possible to bind data to datalist in html5 as we bind data from a datatable to asp.net dropdown control.

Where i can find this details. any pointers is much appreciated. :)

Thanks

Answer

Denys Wessels picture Denys Wessels · Mar 26, 2013

1) Assign runat="server" to the datalist so that it can be accessed from code behind:

Enter your favorite browser name:<br />
<input id="browserName" list="browsers" />
<datalist id="browsers" runat="server" /> 

2) Loop through the DataTable, construct and concatenate a list of options using a StringBuilder and add the result to the InnerHtml property of the datalist

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable table = new DataTable();
        table.Columns.Add("BrowserName");
        table.Rows.Add("IE");
        table.Rows.Add("Chrome");
        table.Rows.Add("Firefox");
        table.Rows.Add("Opera");
        table.Rows.Add("Safari");

        var builder = new System.Text.StringBuilder();

        for (int i = 0; i < table.Rows.Count; i++)
            builder.Append(String.Format("<option value='{0}'>",table.Rows[i][0]));
        browsers.InnerHtml = builder.ToString();
    }

If you're going to need this functionality in multiple places in your site, you can either create a WCF service and call it via jQuery where you can populate the datalist or create an HTTP handler like this:

1)Add a Generic Handler to your project and call it AutoCompleteHandler.ashx

2)Inside AutoCompleteHandler.ashx put:

public class AutoCompleteHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Clear();

        var options = new System.Text.StringBuilder();
        options.Append("<option value='IE'>");
        options.Append("<option value='Chrome'>");
        options.Append("<option value='Firefox'>");
        options.Append("<option value='Safari'>");
        options.Append("<option value='Opera'>");

        context.Response.Write(options.ToString());
        context.Response.End();
    }
    public bool IsReusable
    {
        get{return false;}
    }
}

3)Call the handler via jQuery when the page loads and populate the datalist with the returned result:

<script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $.post('AutoCompleteHandler.ashx', function (data) {
            $('#browsers').html(data);
        });
    });
</script>