Binding data to html5 DataList in asp.net
Asked Answered
H

1

7

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

Herbage answered 26/3, 2013 at 2:38 Comment(0)
A
11

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>
Anethole answered 26/3, 2013 at 8:53 Comment(1)
You went extra mile. Thanks for the detailed answer and references :)Shanonshanta

© 2022 - 2024 — McMap. All rights reserved.