Search code examples
asp.net-mvcasp.net-mvc-3entity-frameworkentity-framework-4asp.net-mvc-4

Populate a <select> list from a server side collection upon the user selecting a value in another list


If a user selects a value from an HTML drop down list A, I want to make an ajax call to the server to populate the values in HTML drop down list B based on the user's selection.

I am using ASP.NET MVC 4 with EF 4. How do I do that?


Solution

  • Listen for the change event of first drop down and then load the content of second drop down in JSON format and inject that to the second drop down

    <select id="country">
      <option value='1'>USA</option>
      <option value='2'>Canada</option>
    </select>
    <select id="States"></select>
    

    and the script

    $(function(){
      $("#country").change(function(){
        var _this=$(this);
        var items="";
        $.getJSON("@Url.Action("GetStates","Country")/"+_this.val(),function(data){
               if(data.Status==="Success")
               {
                  $.each(data.Items,function(index, item){
                     items=+"<option value='"+item.ID+'">"+item.Name+"</option>";
                  });                 
               }
               $("#states").html(items);
        });
      });       
    });
    

    Assuming your GetStates action method returns JSON data with ID and Name as below.

    public ActionResult GetStates(int id)
    {
      List<State> stateList=yourRepositary.GetStatesForCountry(id);
      return Json(new { Status="Success", Items=stateList},
                                               JsonRequestBehaviour.AllowGet);
    }
    

    Assuming GetStatesForCountry method returns a list of State object with ID and Name as properties.