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
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.
Step 4
Now right click on index method return View() and select Add View->OK
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.
- <body>
- <select id="countrySelect" style="width:200px">
- <option>Select Country</option>
- </select>
- </body>
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.
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.
- $.get('controllerUrl', function(data)
- {
-
-
-
- }
Step 7
Now run the application,
And you will get the data from the controller in our select list.