【问题标题】:KnockOut ajax with MVC使用 MVC 淘汰 ajax
【发布时间】:2016-03-27 20:39:45
【问题描述】:

这是我的 KnockOut 控制器类

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);
    }

    }

这是我的索引视图

 @{
 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>``

我正在使用 ajax 调用方法从该索引视图调用 json 数据,但它没有返回任何内容,我的脚本部分有任何问题,请帮助我,我是 Knockout 的新手..

【问题讨论】:

  • 在ajax'done'的情况下,你能看到data参数里面有数据吗?
  • 不,它没有打 ajax 调用

标签: javascript jquery html ajax knockout.js


【解决方案1】:

试试这个

$(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");
    });
});

来自jQuery API docs

$.each() 函数与 $(selector).each() 不同,它是 用于专门迭代 jQuery 对象。 $.each() 函数可用于迭代任何集合,无论是对象还是数组。

【讨论】:

  • 感谢您的回答
猜你喜欢
  • 2015-05-26
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 2018-03-22
  • 2013-06-15
  • 2018-12-23
  • 2019-04-06
相关资源
最近更新 更多