How to create Dropdown List with data From Database In MVC 5.0

I want to bind the data from the database to the dropdownlist in MVC 5.0 and I was getting challenge to achieve this with the Ajax call.

When I run the project, it gives me an error as mentioned below:

 

A circular reference was detected while serializing an object of type ‘System.Data.Entity.DynamicProxies.Fixture_Parts_F1F30332D5D8CD38F7186C1222433736200F97ADF12EF7369E6E4CAE2AA27BE2’.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: A circular reference was detected while serializing an object of type ‘System.Data.Entity.DynamicProxies.Fixture_Parts_F1F30332D5D8CD38F7186C1222433736200F97ADF12EF7369E6E4CAE2AA27BE2’.

 

My Ajax call is

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script>
<script type=”text/javascript”>

$(document).ready(function () {
$.ajax({
url: “ReturnJSONDataToAJax”,
type: “GET”,
//contentType: “application/json; charset=utf-8”,
datatype: JSON,
success: function (result) {
debugger;
$(result).each(function () {
$(“#FromJson”).append($(“<option></option>”).val(this.ID).html(this.Name));
});
},
error: function (data) { }
});
});
</script>

and, my current code from the controller is :

 

public JsonResult ReturnJSONDataToAJax() //It will be fired from Jquery ajax call
{
var s= db.Parts.ToList();
return this.Json(s, JsonRequestBehavior.AllowGet);

}

 

so In order to fix this issue, we need to specify the columns like I fixed my code in the controller as below:

 

public JsonResult ReturnJSONDataToAJax() //It will be fired from Jquery ajax call
{
//var s= db.Parts.ToList();
//return this.Json(s, JsonRequestBehavior.AllowGet);

List<Part> lst = db.Parts.ToList();
//selecting the desired columns
var subCategoryToReturn = lst.Select(S => new
{
ID = S.Part_Id,
Name = S.Part_Name,
});
//returning JSON
return this.Json(subCategoryToReturn, JsonRequestBehavior.AllowGet);
}

 

and it works and filled the data in my dropdownlist.

 

If you want to add “Select XXX” at the top of the dropdownlist then you can refer below code:

$(document).ready(function () {
$.ajax({
url: “ReturnJSONDataToAJax”,
type: “GET”,
//contentType: “application/json; charset=utf-8″,
datatype: JSON,
success: function (result) {
debugger;
$(result).each(function () {
var options = ”;
options += ‘<option value=”Select”>Select a Company</option>’;
for (var i = 0; i < result.length; i++) {
options += ‘<option value=”‘ + result[i].ID + ‘”>’ + result[i].Name + ‘</option>’;
}
$(‘#FromJson’).html(options);
});
},
error: function (data) { }
});
});

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *