Search code examples
asp.netjquerydynamic-rebinding

jQuery-AJAX to rebind dropdown list to results from stored procedure


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.


Solution

  • 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.