【发布时间】:2017-07-21 14:40:34
【问题描述】:
以下代码是常规控制器的一部分(不使用 API),我需要将多个值返回到 knockout.js 文件。问题是,文件正在等待接收 Json,当我发送列表时,我收到一条消息“SyntaxError:位置 0 的 JSON 中的意外令牌 S”,但是如果我更改签名并将对象转换为 JSON,那么异步的 linq 没有运行。
我的问题是,我怎样才能使用异步获取列表(因此它可以在淘汰赛中工作)并且仍然以 JSON 形式发送?或者我应该走哪条路?
public async Task<List<InsDetDTO>> LoadInsDet(int id)
{
var ins = await db.INSPECTIONDETAILS
.Select(t =>
new InsDetDTO()
{
Id = t.ID,
AreaEquipment = t.AreaEquipment,
InspectionID = t.InspectionID
}).Where(t => t.InspectionID == id).ToListAsync();
return ins;
}
旁注,这是我第一次尝试使用淘汰赛,感谢任何信息,是的,我已经在谷歌上搜索了一段时间。
KO
var ViewModel = function () {
var self = this;
//inspection
self.inspections = ko.observableArray();
self.error = ko.observable();
//details
self.detail = ko.observableArray();
var inspUri = '/INSPECTIONs/LoadIns';
var insDetUri = '/INSPECTIONs/LoadInsDet/';
//function ajaxHelper(uri, method, data) {
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
//url: uri,
url: uri,
//async: false,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllInspections() {
ajaxHelper(inspUri, 'GET').done(function (data) {
self.inspections(data);
});
}
self.getInspectionDetails = function (item) {
ajaxHelper(insDetUri + item.Id, 'GET').done(function (data) {
self.detail(data);
});
}
// Fetch the initial data.
getAllInspections();
};
ko.applyBindings(new ViewModel());
查看 检查
<!-- ko if:detail() -->
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Detail</h2>
</div>
<table class="table">
<tr><td>AreaEquipment</td><td data-bind="text: detail().AreaEquipment"></td></tr>
<tr><td>InspectionID</td><td data-bind="text: detail().InspectionID"></td></tr>
</table>
</div>
</div>
<!-- /ko -->
【问题讨论】:
-
我要做的是将url放到浏览器地址栏中的action方法中,最好是chrome,因为它会显示json而不强迫你保存它,然后看看它返回什么。然后分析回报。
-
我得到 [{"Id":2,"InspectionID":12,"AreaEquipment":"f "}] 没关系,问题是它不是异步的
-
它是异步的。 KO 期待什么:一个数组?因为那是一个数组。
-
我添加了 app.js (ko) 和视图
-
你的控制器方法的返回类型是什么?它返回一个 JsonResult 吗?看起来你得到的数据是 JS 而不是 JSON。
标签: c# json asynchronous knockout.js