Friday, March 14, 2014

Populate Select/ListBox items from Html.DropdownList() selected value using jQuery in ASP.NET MVC 4

After familiarizing some basic concepts on ASP.NET MVC 4, I decided to create a simple application which populates a listbox control from a DropDownList helper selected value using jQuery. This simple application included the Entity Framework which targets the AdventureWorks DB.
Here's the Model Class:
Code:
  public class CountryRegionsContext : Models.AdventureWorks2008Entities
    {
        public DbSet<CountryRegion> Country_Regions { get; set; }
        public DbSet<StateProvince> State_Province { get; set; }
    }
Here's the View page:
 @{  
   ViewBag.Title = "Index";  
   Layout = "~/Views/Shared/_Layout.cshtml";  
 }  
 <h2>Adventure Works Country and State Province Information</h2>  
 <script>  
   $(document).ready(function () {  
     $("#State").prop("disabled", true);  
     $("#Country").change(function () {  
       if ($("#Country").val() != "Select") {  
         var CountryProvinces = {};  
         CountryProvinces.url = "/CountryRegions/StateProvinces";  
         CountryProvinces.type = "POST";  
         CountryProvinces.data = JSON.stringify({ Country: $("#Country").val() });  
         CountryProvinces.datatype = "json";  
         CountryProvinces.contentType = "application/json";  
         CountryProvinces.success = function (StateProvinceList) {  
           $("#State").empty();  
           if (StateProvinceList != undefined) {  
             if (StateProvinceList.length > 0) {  
               for (var i = 0; i < StateProvinceList.length; i++) {  
                 $("#State").append("<option>" + StateProvinceList[i] + "</option>");  
               }  
               $("#State").prop("disabled", false);  
             }  
             else  
               alert("No State or Region for that Country!");  
           }  
           else {  
             alert("No State or Region for that Country!");  
           }  
         };  
         CountryProvinces.error = function ()  
         {  
           alert("Error in Retrieving State Province Information!");  
         };  
         $.ajax(CountryProvinces);  
       }  
       else {  
         $("#State").empty();  
         $("#State").prop("disabled", true);  
       }  
     });  
   });  
 </script>  
 @using (Html.BeginForm("Index", "CountryRegions",   
   FormMethod.Post,  
   new { id = "countryRegionsForm" }))  
 {  
   @Html.AntiForgeryToken()  
   <h4>Select Country & States</h4>  
   <hr />  
    @Html.ValidationSummary()  
   <div>  
     @Html.Label("Select Country:")  
     <div>  
       @Html.DropDownList("Country", ViewData["CountryInfo"] as SelectList)  
     </div>  
   </div><br />  
   <div>  
     @Html.Label("State Province")  
     <div>  
        <select id="State" name="lstStates" size="15" style="width:300px;"></select>  
     </div>  
   </div>  
 }  
Here's the controller class:
Code:
public class CountryRegionsController : Controller
    {
        private CountryRegionsContext context = new CountryRegionsContext();
        private List<CountryRegion> CountryNameList = new List<CountryRegion>();
        private List<string> StateProvinceList = new List<string>();

        // GET: /CountryRegions/
        public ActionResult Index()
        {            
            SelectList countries;
            if (context.Country_Regions.ToList().Count > 0)
            {
                CountryNameList.AddRange(context.Country_Regions.ToList().OrderBy(t => t.Name));
                countries = new SelectList(CountryNameList, "CountryRegionCode", "Name");
                ViewData["CountryInfo"] = countries;
            }
            
            return View();
        }

        public JsonResult StateProvinces(string Country)
        {
            (from province in context.State_Province
            where province.CountryRegionCode == Country
            select new
            {
                name = province.Name
            }).ToList().ForEach(data => 
                {
                    StateProvinceList.Add(data.name);
                }); 
                      
            return Json(StateProvinceList);
        }
}
Sample output page without record:
Sample output page with record:

0 comments:

Post a Comment