Hi sallmomar,
Due to the error A circular reference was detected while serializing an object it is not displaying.
To avoid the error create a ViewModel which is identical to your structure or with required properties and pass the ViewModel to return JsonResult.
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Controller
// GET: /Home/
public ActionResult Index()
{
return View();
}
public JsonResult ReturnDropDownListItem()
{
NorthwindEntities entities = new NorthwindEntities();
List<lsite> lists = entities.Employees
.Select(x => new lsite
{
FirstName = x.FirstName,
LastName = x.LastName
}).ToList();
return Json(lists, JsonRequestBehavior.AllowGet);
}
public ActionResult GetInfo(string name)
{
NorthwindEntities db = new NorthwindEntities();
if (!string.IsNullOrWhiteSpace(name))
{
List<Employee> resultats = db.Employees.Where(t => t.FirstName == name)
.Select(x => new Employee
{
Id = x.EmployeeID,
Nom_de_site = x.FirstName + " " + x.LastName
}).ToList();
return Json(resultats, JsonRequestBehavior.AllowGet);
}
return null;
}
}
public class lsite
{
public string LastName { get; set; }
public string FirstName { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Nom_de_site { get; set; }
}
View
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function () {
$.getJSON('Home/ReturnDropDownListItem', function (response) {
$(response).each(function () {
$("#Lsite").append($("<option></option>").val(this.FirstName).html(this.LastName));
});
});
$('[id*=Lsite]').change(function () {
var selectedCountry = $(this).find('option:selected').val();
if (selectedCountry != null && selectedCountry != '') {
$.getJSON('Home/GetInfo', { name: selectedCountry }, function (response) {
if (response.length > 0) {
$("[id*=tblEmployees] tbody").empty();
var row;
$.each(response, function (recherche, item) {
row += "<tr><td>" + item.Id + "</td><td>" + item.Nom_de_site + "</td></tr>"
})
$("[id*=tblEmployees] tbody").append(row);
}
}).fail(function (response) {
});
}
});
});
</script>
<table>
<tr>
<td>
<%:Html.DropDownList("Lsite", new SelectList(Enumerable.Empty<lsite>(),
"FirstName", "LastName"), "Select Site", new { @class = "form-control", id = "Lsite" }) %>
</td>
</tr>
</table>
<table id="tblEmployees">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Screenshot