Reputation: 462
I am trying to load data from controller using ajax.
Controller
[HttpGet]
public ActionResult GetServices()
{
var data = _bbdb.ListServices.Where(d => d.Status == true).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
View
<div class="one-third column omega">
<div class="title-wrapper">
<div class="section-title">
<h4 class="title">Services <strong>Availables</strong></h4>
</div>
<span class="divider"></span>
<div class="clear"></div>
</div>
<ul class="accordion" id="ListServices">
</ul>
</div>
<div class="clear"></div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '@Url.Action("Home/GetServices")',
contentType: "application/json; charset=utf-8",
cache: false,
global: false,
async: false,
dataType: "json",
success: function (data) {
alert(data);
$.each(data, function () {
$("<li/>").html('<li><div class="parent first"><h6><div class="accordion-caption"></div>' + this.Title + '</h6></div><div class="tcontent"><p>' + this.Description + '</p></div></li>').appendTo("#ListServices");
});
},
error: function (error) {
alert(error);
}
});
});
</script>
However it does not display the data from the controller, instead it display alert with [object][object].
The returned data should be a list of values used to populate the accordion.
What am I missing here?
Any help will be much appreciated.
Upvotes: 0
Views: 868
Reputation: 3702
Now that you have your URL straight (see comments on OP), lets look at your success callback.
success: function (data) {
alert(data);
$.each(data, function () {
// your html creation here
});
},
You need to add the parameters to the $.each
, like so
$.each(data, function(index, val){
console.log(val.Title);
console.log(val.Description);
});
See jQuery .each() documentation for more info on that.
Also, when you are appending your HTML to your <ul>
, all you have to do is this:
$('#ListServices').append('<li><div>Rest of your HTML...</div></li>');
Upvotes: 1