Hi ngoctuan04th2,
Refer below sample.
Database
For this o have used Northwind database. You can download from below link.
Download Northwind Database
Model
public class EmployeeModel
{
[Display(Name = "Select City")]
public string City { get; set; }
}
Namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View(new EmployeeModel());
}
[HttpGet]
public JsonResult CityList()
{
List<SelectListItem> cities = new List<SelectListItem>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
{
string query = "SELECT DISTINCT EmployeeID,City FROM Employees";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
cities.Add(new SelectListItem()
{
Text = sdr["City"].ToString(),
Value = sdr["EmployeeID"].ToString()
});
}
}
con.Close();
}
}
return Json(cities, JsonRequestBehavior.AllowGet);
}
}
View
@model Chosen_DropDownList_jQuery_Ajax.Models.EmployeeModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css">
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Home/CityList",
data: "{}",
success: function (data) {
$("#City").empty().append('<option Value="0">All</option>');
// Insert each other element
$.each(data, function (i) {
$("#City").append('<option Value="' + data[i].Value + '">' + data[i].Text + '</option>');
});
$('#City').chosen();
}
});
});
</script>
</head>
<body>
@using (Html.BeginForm())
{
@Html.DropDownListFor(model => model.City, Enumerable.Empty<SelectListItem>(), new { @id = "City", @class = "chosen-select", style = "width: 150px;" })
}
</body>
</html>
Screenshot