Asp.net MVC populate a list box with JQuery?

12,487

Solution 1

Your reasoning so far is totally sound. First you are going to want to include the jquery library in your View / Master. You can download a copy of jquery from http://jquery.com/. Add the file to you project and include a <script src="/path/to/jquery.js"> to the <head> of your document. You are going to want to add another dropdown to your View (and probably another property to your model). We'll call this 'SelectedCategoryId:'

<%=Html.DropDownList("SelectedCategoryId", null, "Select One...", new { style = "display:none;"}) %>

We've set the style of this Drop Down to not be visible initially because there is nothing to select inside of it. We'll show it later after we generate some content for it. Now, somewhere on your page you will want to include a <script> block that will look something like this:

$(document).ready(function() { $('#SelectedPayeeId').change(function() { 
$.ajax({
  type: 'POST',
  url: urlToYourControllerAction,
  data: { payeeId: $(this).val() },
  success: function(data) { 
     var markup = '';
     for (var x = 0; x < data.length; x++ ) {
        markup += '<option value="' + data[x].Value + '">'+data[x].Text+'</option>';
     }
     $('#SelectedCategoryId').html(markup).show();
  }
}); }); });

This code binds the anonymous function written above to the DOM element with the ID of 'SelectedPayeeId' (in this case your dropdown). The function performs an AJAX call to the url of your method. When it receives the results of the request (your JSON you returned) we iterate over the array and build a string of the html we want to inject into our document. Finally we insert the html into the 'SelectedCategoryId' element, and change the style of the element so it is visible to the user.

Note that I haven't run this code, but it should be (almost) what you need. jQuery's documentation is available at http://docs.jquery.com/Main_Page and the functions I used above are referenced here:

Solution 2

You'd need to make the GetCategories as a public method as it would correspond to an action handler in your controller.

Your jquery code can look like:

<script type="text/javascript">
    $(function() {
 $('#SelectedPayeeId').change(function() {
          $.get('<%= Url.Action("GetCategories", "YourControllerName") %>',
                    {payeeId: $(this).val()}, 
                    function(data) {
                       populateSelectWith($("#Category"), data);

           });
        });
   //Place populateSelectWith method here
});
</script>
The populateSelectWith can fill your dropdown with data like:

  function  populateSelectWith($select, data) {
    $select.html('');
    $select.append($('<option></option>').val('').html("MYDEFAULT VALUE"));
    for (var index = 0; index < data.length; index++) {
        var option = data[index];
        $select.append($('<option></option>').html(option));
      }
    }

I have not tested this code, but I am hoping it runs okay.

You can find syntax for the jquery ajax get here Since you are not posting any data to the server, you can might as well decorate your controller action with a [HttpGet] attribute

Share:
12,487
Craig
Author by

Craig

I'm a Development Team Lead for a small company in Brisbane, Australia, with interests in SQL Server, .Net application development, and some ReactJS, but ... I don't like frontend dev. :(

Updated on June 09, 2022

Comments

  • Craig
    Craig almost 2 years

    I have a list of Payees in a drop down box on my form. I would like to populate a different drop down, based on the selected item of the Payee drop down, without post backs and all that.

    So, I created a method in my controller that does the work:

            private JsonResult GetCategories(int payeeId)
        {
            List<CategoryDto> cats = Services.CategoryServices.GetCategoriesByPayeeId(payeeId);
            List<SelectListItem> items = new List<SelectListItem>();
    
            foreach(var cat in cats)
            {
                items.Add(new SelectListItem {Text = cat.Description, Value = cat.CategoryId.ToString()});
            }
    
            return Json(items);
    
        }
    

    Now, I am unsure what to add to my view to get this to work.

    At the moment, all I have is this:

     <% using (Html.BeginForm())
       {%>
    
       <p>
       <%=Html.DropDownList("SelectedAccountId", Model.Accounts, "Select One..", null) %>
       </p>
       <p>
       <%=Html.DropDownList("SelectedPayeeId", Model.Payees, "Select One...", null) %>
       </p>
    
                             <input type="submit" value="Save" />
    <%
        }%>
    

    they populate fine... so when the user selects the SelectedPayeeId drop down, it should then populate a new (Yet to be created?) drop down which holds categories, based on the SelectedPayeeId.

    So, I think I need to create a JQuery function (Never done JQuery.. so not even sure where it goes) which monitors the Payee drop down for an onChange event? And then call the method I created above. Does this sound right, and if so, can you guide me in how to achieve this?