2

I have a dropdown list of peoples names that is quite long. As many as 2,000 names. I would like to make it easier to find the name the user is interested in by limiting the dropdown list to a subset of names at a time. I have done this by creating a series of 26 links (A, B, C ... Z) that call a method in the code behind that populates the dropdown list with only those names starting with the letter the user clicked.

This all works well but I would like to be able to use AJAX to accomplish this update of the dropdown list without a page refresh. I would like to use jQuery for the AJAX functionality rather than ASP.NET AJAX.

My problem is I am not sure how to execute the stored procedure and then "rebind" the dropdown list with the new dataset via jQuery AJAX. Any suggestions or resources that might provide and example or walk-through? Thank you.

webworm
  • 10,587
  • 33
  • 120
  • 217

2 Answers2

6

Some direction for you.

First create a page, webservice, or httphandler that will take your post and return back json.

Handler:

public void GetNames(HttpContext context)
{
    context.Response.ContentType = "application/json";
    context.Response.ContentEncoding = Encoding.UTF8;

    var results = DataAccess.GetNames(context.Request["letter"]);

    string json = //encode results to json somehow, json.net for example.

    context.Response.Write(json );
}

The Markup

<ul>
  <li>A</li>
</ul>

<select id="names">
</select>

The Script to do a $.post

$(function(){
  $("li").click(function(){
    var letter = $(this).text();
    $.post("SomeUrl/GetNames", {letter: letter}, function(data){
     var $sel = $("#names").empty();
     $.each(data, function(){
       //this assumes the json is an array in the format of {value: 1, name:'joe'}
       $sel.append("<option value='" + this.value + "'>" + this.name+ "</option>");
     });
    }, "json");
  });
});

That should be a good outline on how to accomplish your task.

Some additional resources.

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
  • +1 for great example. I am afraid I might need a little more "handholding" on this one. Any suggestions on tutorials or articles that might cover this? I am not so familiar with using context and JSON. – webworm Mar 03 '11 at 16:36
  • @webworm, updated the answer with some resources that could be of some help. – Mark Coleman Mar 03 '11 at 16:46
0

The jQuery Autocomplete plugin might be a valid solution for you.

Ryan Miller
  • 391
  • 1
  • 12
  • Thanks, but I would really like to learn how to rebind the results of the stored procedure back to the dropdown list via jQuery-AJAX "manually" on not depend on a plugin. Besides, I would like to avoid having to bind 2,000 names to the dropdown. – webworm Mar 03 '11 at 15:34