Filling Dropdown List (Html Select List) Dynamically Using ASP.NET MVC and JQuery Ajax

We are going to use ASP.NET MVC,Jquery, and Ajax and to understand this topic you should know the basics of html, Jqery, and Asp.net mvc. In this example I am going to fill various country names in the dropdownlist which will be fetched from controller.

Step 1

Create a New Project

Go TO File -> New -> Select Empty and Checked MVC -> OK

NEW

Step 2

Now Right Click on Controllers -> Add -> New Controller -> Name it as HomeController

Step 3

There is default method Index leave it as it is.

Now write a new method, I have named it countrySelectList() whose return type is JsonResult it is returning the list of of countries in Json format.

We are going to use this countrylist to fill up our select list.

In this method I have not used any data fetched from the database but you can get the data from the database and put it in the List object; the rest remains the same.

code

Step 4

Now right click on index method return View() and select Add View->OK

index

Step 5

Now go to the Index.cshtml,

In the body part write code for selectlist and give id to it which helps us while filling the data in it.

  1. <body>  
  2.     <select id="countrySelect" style="width:200px">  
  3. <option>Select Country</option>   
  4. </select>  
  5. </body>  
code

Step 6

Now to Add the countries to select list we use jquery.

In the head part write script tags and the code given in the image.

code

Explanation of script code

$(document).ready --> keeps the function from executing while the page is fully loaded and after that executes the code in it.
  1. $.get('controllerUrl', function(data)   
  2.       {  
  3.             //we get the data(countrylist in json) from controller in this function we can also call it as response from the server.  
  4.             //do operations  
  5.             //$.each() is used to iterate over any collection which is object or an array and we are adding each item in the collection in the select as option and finally we get all the countries in the select list.  
  6.         }  
Step 7

Now run the application,

application  
And you will get the data from the controller in our select list.