Updating Drop Downs w/ ASP.NET MVC and jQuery

Updating Drop Downs w/ ASP.NET MVC and jQuery

January 25th, 2009  |  Published in Programming

I’ve been getting in to the ASP.NET MVC Framework and so far I am enjoying it but, it’s not always easy. One area that I am having to get used to is using jQuery to implement some ajax functions because I was always a fan of the Microsoft AJAX Library. In perticular I use drop downs a great deal in order to filter through large datasets – so here are a number of solutions/reading material for anyone who is interested.

As a test project I am rewriting my custom bug report application:

Doing the inital load of the drop downs

private void LoadInitialDropDowns()
{
    var Projects = (from projects in dbData.tbl_Projects
                    where projects.Company_ID == 3
                    select new { projects.Title, projects.Project_ID }).Distinct();

    ViewData["Projects"] = new SelectList(Projects, "Project_ID", "Title");

    var Companies = (from companies in dbData.tbl_Companies
                     select new { companies.Comapny_Name, companies.Company_ID }).Distinct();

    ViewData["Companies"] = new SelectList(Companies, "Company_ID", "Comapny_Name");
}

The View

<label>
    Company:
    <span class="small"> </span>
</label>
<%= Html.DropDownList("Companies") %>

<label>
    Project:
    <span class="small"> </span>
</label>
<%= Html.DropDownList("Projects") %>

<script type="text/javascript">
    $(function() {
        $('select#Companies').change(function() {
        $.getJSON('/Tickets/GetUpdatedProject/' + $('select#Companies').val(), { id: this.value },
                  function(response) {
                      var options = '';
                      for (var i = 0; i < response.length; i++) {
                          options += "<option value='" + response[i].Project_ID + "'>"
                              + response[i].Title + "</option>";
                      }
                      $('select#Projects').removeAttr('disabled').html(options);
                });
        });
    });
</script>

Exporting the results via Json

public ActionResult GetUpdatedProject(int id)
{
    var Projects = (from projects in dbData.tbl_Projects
                    where projects.Company_ID == id
                    select new { projects.Title, projects.Project_ID }).Distinct();

    return Json(Projects.ToList());
}

Additional Reading:

Update a DropDrownList in a ASP.NET MVC when a user select un option in another DropDrownList – [I borrowed pretty heavily from here. I will also be re-factoring this a most a new version shortly]

Load Drop Down with jQuery

Create Cascading Dropdown Lists with Ajax



Related Posts

ASP.NET MVC Links
Haack MVC Video: Cross-site Request Forgery Attack
Problems with Html.DropDownList

Leave a Response


Archives

Categories

Calendar

March 2010
S M T W T F S
« Feb    
 123456
78910111213
14151617181920
21222324252627
28293031