Bind Strongly Typed DropDownList Using JSON In ASP.NET MVC 5

Background
 
Many times we need to bind the strongly typed DropDownList using JSON data in ASP.NET MVC . So by considering above requirement I have decided to write this article . Let us learn it step by step through creating a simple MVC application.
Step 1: Create an MVC application.
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".

  2. "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.

  3. Choose MVC empty application option and click on OK
Step 2: Add model class.

Right click on model folder of created MVC application project and add class file named EmpModel.cs and create two classes as:

EmpModel.cs
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace BindDropDownListUsingJSON.Models  
  4. {  
  5.     //Model property to the dropdownlist to get selected value  
  6.     public class EmpModel  
  7.     {  
  8.         [Display(Name = "Select City")]  
  9.         public string City { getset; }  
  10.     }  
  11.     //to bind list of records to dropdownlist  
  12.     public class DDLOptions  
  13.     {  
  14.        public int Id { getset; }  
  15.        public string CityName { getset; }  
  16.   
  17.    }  

 Step 3: Add controller class.

Right click on Controller folder in the created MVC application, give the class name Home or as you wish as in the following:


Now after selecting controller template, click on Add button then the following window appears,



Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class as in the following:
  1. using BindDropDownListUsingJSON.Models;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Mvc;  
  5.   
  6. namespace BindDropDownListUsingJSON.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         // GET: Home  
  11.         public ActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.          
  16.         //Return json list of cities  
  17.         [HttpGet]  
  18.         public JsonResult CityList()  
  19.         {  
  20.             List<DDLOptions> obj = new List<DDLOptions>()  
  21.             {  
  22.                 new DDLOptions {Id=1, CityName="Latur" },  
  23.                 new DDLOptions {Id=2, CityName="Pune" },  
  24.                 new DDLOptions {Id=4, CityName="Mumbai"},  
  25.                 new DDLOptions {Id=5, CityName="New Delhi" }  
  26.             }.ToList();  
  27.   
  28.             return Json(obj, JsonRequestBehavior.AllowGet);  
  29.         }  
  30.     }  

In the above we have created two action methods one is return view named Index and another one will return json result named CityList. Remember that instead of going to the database I have created a list of records and return it as json. However you can bind this list from database but in this example assume that this list is coming from database.

Step 4: Add View,

Add strongly typed view named Index.cshtml from EmpModel class as:
 
 

After clicking on add button the view generated.

To call the CityList json action method, create the following jQuery Ajax function.
  1. <script>  
  2.       
  3.     $(document).ready(function ()  
  4.     {    //call the CityList json result method  
  5.         $.getJSON("/Home/CityList"function (data)  
  6.         {        
  7.             $.each(data, function (i, data)  
  8.             {      // bind the dropdown list using json result              
  9.                  $('<option>',  
  10.                     {  
  11.                         value: data.Id,  
  12.                         text: data.CityName  
  13.                     }).html(data.CityName).appendTo("#City");  
  14.                 });  
  15.         })  
  16.         //Get the selected text on button click  
  17.         $("#btnSave").click(function () {  
  18.   
  19.             var txt = $("#City option:selected").text();  
  20.             
  21.             // assign the selected value to span to   
  22.             //show to the end user  
  23.             $("#Spnmsg").text("Your Selected City is " + txt);  
  24.   
  25.             return false;  
  26.   
  27.         })  
  28.   
  29.     });  
  30. </script> 
To work the above function properly we need the following jQuery file to be referenced at the top of the view or in layout page.
  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script> 
After adding necessary code, files and logic the Index.cshtml code will look like the following,
  1. @model BindDropDownListUsingJSON.Models.EmpModel  
  2. @{  
  3.     ViewBag.Title = "www.compilemode.com";  
  4. }  
  5. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  6. <script>  
  7.       
  8.     $(document).ready(function ()  
  9.     {    //call the CityList json result method  
  10.         $.getJSON("/Home/CityList", function (data)  
  11.         {        
  12.             $.each(data, function (i, data)  
  13.             {      // bind the dropdown list using json result              
  14.                  $('<option>',  
  15.                     {  
  16.                         value: data.Id,  
  17.                         text: data.CityName  
  18.                     }).html(data.CityName).appendTo("#City");  
  19.                 });  
  20.         })  
  21.         //Get the selected text on button click  
  22.         $("#btnSave").click(function () {  
  23.   
  24.             var txt = $("#City option:selected").text();  
  25.             
  26.             // assign the selected value to span to   
  27.             //show to the end user  
  28.             $("#Spnmsg").text("Your Selected City is " + txt);  
  29.   
  30.             return false;  
  31.   
  32.         })  
  33.   
  34.     });  
  35. </script>  
  36.   
  37. @using (Html.BeginForm())   
  38. {  
  39.     @Html.AntiForgeryToken()  
  40.       
  41.     <div class="form-horizontal">  
  42.          
  43.         <hr />  
  44.         @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  45.         <div class="form-group">  
  46.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  47.             <div class="col-md-12">  
  48.                 @Html.DropDownListFor(model => model.City, Enumerable.Empty<SelectListItem>(), new { htmlAttributes = new { @class = "form-control" } })  
  49.         
  50.                  
  51.             </div>  
  52.         </div>  
  53.   
  54.         <div class="form-group">  
  55.             <div class="col-md-offset-2 col-md-10">  
  56.                 <input type="submit" value="Save" id="btnSave" class="btn btn-primary" />  
  57.             </div>  
  58.         </div>  
  59.         <div class="form-group">  
  60.             <div  class="col-md-offset-2 col-md-10 text-success">  
  61.                 <span id="Spnmsg"></span>  
  62.                
  63.             </div>  
  64.         </div>  
  65.     </div>  

Step 5: Run the application.

After running the application the output will be as in the following screenshot:
 
 
In the preceding screenshot you have seen that drop down list records are populated from json data. Now select any city from drop down list records and click on save button, it will show the following output.
 
From all the above examples, I hope you have learned how to bind strongly typed dropdownlist using JSON data in ASP.NET MVC .

Note:
  • For the complete code, please download the sample zip file.
  • You need to use the jQuery library.
Summary

I hope this article is useful for all readers. If you have a suggestion then please contact me.

Up Next
    Ebook Download
    View all
    Learn
    View all