DropDownList Using JSON Data In ASP.NET MVC

In this article, we will learn how to bind the DropDownList using JSON data in ASP.NET MVC. Let's learn it step by step through creating a simple ASP.NET 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 ASP.NET MVC empty application option and click on OK

Step 2: Add model class.

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

EmpModel.cs
using System.ComponentModel.DataAnnotations;  
  
namespace BindDropDownListUsingJSON.Models  
{  
    //Model property to the dropdownlist to get selected value  
    public class EmpModel  
    {  
        [Display(Name = "Select City")]  
        public string City { get; set; }  
    }  
    //to bind list of records to dropdownlist  
    public class DDLOptions  
    {  
       public int Id { get; set; }  
       public string CityName { get; set; }  
  
   }  
}  

Step 3: Add controller class.

Right click on Controller folder in the created ASP.NET 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:
using BindDropDownListUsingJSON.Models;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web.Mvc;  
  
namespace BindDropDownListUsingJSON.Controllers  
{  
    public class HomeController : Controller  
    {  
        // GET: Home  
        public ActionResult Index()  
        {  
            return View();  
        }  
         
        //Return json list of cities  
        [HttpGet]  
        public JsonResult CityList()  
        {  
            List<DDLOptions> obj = new List<DDLOptions>()  
            {  
                new DDLOptions {Id=1, CityName="Latur" },  
                new DDLOptions {Id=2, CityName="Pune" },  
                new DDLOptions {Id=4, CityName="Mumbai"},  
                new DDLOptions {Id=5, CityName="New Delhi" }  
            }.ToList();  
  
            return Json(obj, JsonRequestBehavior.AllowGet);  
        }  
    }  
}  
In the above we have created two action methods. One returns a view named Index and another one will return a json result named CityList. Remember that instead of going to the database I have created a list of records and returned it as json. However you can bind this list from the database, but in this example assume that this list is coming from the 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.
<script>  
      
    $(document).ready(function ()  
    {    //call the CityList json result method  
        $.getJSON("/Home/CityList", function (data)  
        {        
            $.each(data, function (i, data)  
            {      // bind the dropdown list using json result              
                 $('<option>',  
                    {  
                        value: data.Id,  
                        text: data.CityName  
                    }).html(data.CityName).appendTo("#City");  
                });  
        })  
        //Get the selected text on button click  
        $("#btnSave").click(function () {  
  
            var txt = $("#City option:selected").text();  
            
            // assign the selected value to span to   
            //show to the end user  
            $("#Spnmsg").text("Your Selected City is " + txt);  
  
            return false;  
  
        })  
  
    });  
</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.
<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
@model BindDropDownListUsingJSON.Models.EmpModel  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script>  
      
    $(document).ready(function ()  
    {    //call the CityList json result method  
        $.getJSON("/Home/CityList", function (data)  
        {        
            $.each(data, function (i, data)  
            {      // bind the dropdown list using json result              
                 $('<option>',  
                    {  
                        value: data.Id,  
                        text: data.CityName  
                    }).html(data.CityName).appendTo("#City");  
                });  
        })  
        //Get the selected text on button click  
        $("#btnSave").click(function () {  
  
            var txt = $("#City option:selected").text();  
            
            // assign the selected value to span to   
            //show to the end user  
            $("#Spnmsg").text("Your Selected City is " + txt);  
  
            return false;  
  
        })  
  
    });  
</script>  
  
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
         
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-12">  
                @Html.DropDownListFor(model => model.City, Enumerable.Empty<SelectListItem>(), new { htmlAttributes = new { @class = "form-control" } })  
        
                 
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Save" id="btnSave" class="btn btn-primary" />  
            </div>  
        </div>  
        <div class="form-group">  
            <div  class="col-md-offset-2 col-md-10 text-success">  
                <span id="Spnmsg"></span>  
               
            </div>  
        </div>  
    </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.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode