This is My KnockOut Controller Class
public class KnockoutController : Controller
{
//
// GET: /Knockout/
private DataLayer data;
public KnockoutController()
{
data=new DataLayer();
}
public ActionResult Index()
{
return View();
}
public ActionResult Grid()
{
ArrayList rows = new ArrayList();
List<Category> categories = data.RetrivingCategories();
foreach (var category in categories)
{
rows.Add(new { Id = category.Id, cell = new object[] { category.Id,
category.Name } });
}
var jsonData = new
{
rows
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
And This is My Index View
@{
ViewBag.Title = "Test";
}
<h2>Index</h2>
<title></title>
<script src="~/Scripts/jquery-ui-1.8.20.js"></script>
<script src="~/Scripts/knockout-2.1.0.debug.js"></script>
<script src="~/Scripts/knockout-2.1.0.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
<table class="table">
<tr>
<th>
Key
</th>
<th>
Value
</th>
<th></th>
</tr>
<tbody data-bind="foreach: lookupCollection">
<tr>
<td data-bind="text: Key"></td>
<td data-bind="text: Value"></td>
</tr>
</tbody>
</table>
<script>
viewModel = {
lookupCollection: ko.observableArray()
};
$(function () {
$.ajax({
type: "GET",
url: "@Url.Action("Grid", "Knockout")",
}).done(function (data) {
$(data).each(function (index, element) {
var mappedItem =
{
Id: ko.observable(element.id),
Key: ko.observable(element.name),
};
viewModel.lookupCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error");
});
});
</script>``
I am Calling json data from this index view using ajax call method but it's not returning anything, Any problem on my Script Part, Please help me , i am new to the Knockout..
Try this
$(function () {
$.ajax({
type: "GET",
url: "@Url.Action("Grid","Knockout")",
}).done(function (data) {
$.each(data, function (index, element) {
var mappedItem = {
Id: ko.observable(element.id),
Key: ko.observable(element.name),
};
viewModel.lookupCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error");
});
});
From the jQuery API docs,
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.