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)
- {
- //we get the data(countrylist in json) from controller in this function we can also call it as response from the server.
- //do operations
- //$.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.
- }
Now run the application,
And you will get the data from the controller in our select list.
Sarmad YousifPosted Aug 13, 2019, 10:50 AM
Hi i get this error Unhandled exception at line 44, column 9 in http://localhost:19851/Home/Index0x800a1391 - JavaScript runtime error: '$' is undefined next to (document) thank you
Re PinhoPosted Nov 24, 2017, 11:03 AM
Hello, I'm trying to implement in my work but I can not. Can I send you the code to give me a hand, please?I'm working with vb.net MVC