如何在 asp.net mvc 中更改 json 格式?
2018-07-10
409
我正在尝试使用此链接制作自动完成文本框
https://github.com/devbridge/jQuery-Autocomplete
但我收到此错误 未捕获的 TypeError:无法读取未定义的属性“length”
这是我的操作方法
public JsonResult GetNews(string prefix)
{
var newsList = NewsDataRoot.AutoCompleteTitle(prefix).Select(n => new
{
value = n.Title,
data = n.Id
}).ToList();
var myjson = Json(newsList, JsonRequestBehavior.AllowGet);
return myjson;
}
当我在浏览器中测试它时,它返回此结果
[{"value":"this is a test","data":2006}]
我发现格式必须是
{
suggestions: [{
"value": "United Arab Emirates",
"data": "AE"
}, {
"value": "United Kingdom",
"data": "UK"
}, {
"value": "United States",
"data": "US"
}, {
"value": "United Funes",
"data": "DAN"
}]
}
如何做到这一点?非常感谢!
此外,正如您所见,我尝试了 transformResult,但没有成功
<script>
$('#autocomplete').autocomplete({
serviceUrl: '/TestAutoComplete/GetNews',
paramName: 'prefix',
transformResult: function(response) {
return {
suggestions: $.map(response.myData, function(dataItem) {
return { value: dataItem.valueField, data: dataItem.dataField };
})
};
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
</script>
2个回答
尝试一下,创建一个仅具有
suggestions
属性的匿名对象
var newsList = NewsDataRoot.AutoCompleteTitle(prefix)
.Select(n => new {
value = n.Title,
data = n.Id
}).ToList();
var myjson = Json(new { suggestions = newsList }, JsonRequestBehavior.AllowGet);
Kevin Smith
2018-07-10
如果您想将数字设置为数字字符串,您可以尝试将其值转换为字符串
public JsonResult GetNews(string prefix)
{
var newsList = NewsDataRoot.AutoCompleteTitle(prefix).Select(n => new
{
value = n.Title,
data = n.Id.ToString()
}).ToList();
var myjson = Json(new {suggestions = newsList}, JsonRequestBehavior.AllowGet);
return myjson;
}
mshouman
2018-07-10