Hi nabilabolo,
Check this example. Now please take its reference and correct your code.
I am typing customerid in textbox and the data based on the customerid is binded in the dropdownlist.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetData(string id)
{
NorthwindEntities db = new NorthwindEntities();
List<SelectListItem> items = new List<SelectListItem>();
if (!string.IsNullOrEmpty(id))
{
List<Order> orders = db.Orders.Where(o => o.CustomerID.Contains(id)).ToList();
foreach (Order order in orders)
{
items.Add(new SelectListItem
{
Value = order.OrderID.ToString(),
Text = Convert.ToDecimal(order.Freight).ToString("N2")
});
}
}
return Json(items, JsonRequestBehavior.AllowGet);
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript">
$(function () {
$('#txtId').on('keyup', function () {
var param = { id: $('#txtId').val() };
$.getJSON('/Home/GetData', param, function (data) {
var ddlFreights = $('#ddlFreights');
$(ddlFreights).empty();
$(ddlFreights).append('<option value=0>Please Select</option>');
for (var i = 0; i < data.length; i++) {
$(ddlFreights).append('<option value="' + data[i].Value + '">' + data[i].Text + '</option>');
}
}).fail(function (d) { debugger; });
});
});
</script>
</head>
<body class="container">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<input id="txtId" type="text" class="form-control" />
</div>
</div>
<div class="col-sm-6">
<div class="input-group">
<select id="ddlFreights" class="form-control"></select>
</div>
</div>
</div>
</body>
</html>
Screenshot