Reputation: 37
I am having strange problem with Json.
I am making an ajax call to a Controller method which is taking a string as a input and sends back a List of my class.
Basically, I am making the json call on change of dropdown menu, for loading the corresponding fields of another dropdown menu.
In dropdown menu 1, i have 2 options and a placeholder("Select").
The strange thing is that, when i am selecting the 2 option, it is adding the data to the dropdown menu 2. But if i select the option 1, Then it is not getting data in json call, hence not adding anything to the dropdown menu 2, although my controller function is returning the data in json.
My json call is below:
function changeTable() {
var index = 0;
var info = { majoraccountvalue: document.getElementById("expancesMajorAccount").value };
var dropdowm = $("#expancesMinorAccountName");
jQuery.ajax({
type: "POST",
url: "@Url.Action("GetData")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(info),
success: function (data) {
debugger;
var arr = data.MinorAccountHeads;
dropdowm.empty()
alert(data);
for (index = 0; index < arr.length; index++) {
dropdowm.append($('<option></option>').val(arr[index].ID).html(arr[index].Name));
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
And my controller method is:
public JsonResult GetData(long majoraccountvalue)
{
Myclass model = new myclass();
model.FillData(majoraccountvalue);
return Json(new { model.MinorAccountHeads });
}
My controller function is returning data in both the cases. When i select the option 1 as well as if i select option 2.
Thanks
Upvotes: 0
Views: 133
Reputation: 169
I was able to resolve the error. Since, the person know me in person, i was able to help him resolve it.
Basically, problem was with the serialization of the Data which is being sent by the function: public JsonResult GetData(long majoraccountvalue)
The function is returning the Json data by serializing the model.MinorAccountHeads list of custom database entites objects.
There was a self referencing loop while serializing using the method code above.
I was able to resolve it by changing the method by using the Newtonsoft.json library as: public object GetData(long majoraccountvalue) { Myclass model = new myclass(); model.FillData(majoraccountvalue); return JsonConvert.SerializeObject(model.MinorAccountHeads); }
Upvotes: 1
Reputation: 41
Upvotes: 0