正如标题所说,我在这方面遇到了一些麻烦。我成功地对JSON进行了硬编码,但是一旦我开始使用模型就出错了。请看下面我的日期。
的Ajax
$(document).ready(function () {
$.getJSON('/Programs/GetAll', function (data) {
//clear the current content of the select
$('#ProgramId').empty();
//iterate over the data and append a select option
$.each(data, function (key, val) {
$('#ProgramId').append('<option id="' + key + '">' + val + '></option>');})
});
});
控制器
[HttpGet]
public JsonResult GetAll()
{
var progams = _context.Program
.Select(a => new
{
id = a.Id.ToString(),
name = a.Name
}).ToList();
return Json(progams);
}
这种硬编码适用于ajax,js和html。
[HttpGet]
public JsonResult Get()
{
Dictionary<string, string> programSelectList = new Dictionary<string, string>();
programSelectList.Add("1", "Bob");
programSelectList.Add("2", "Cratchett");
return Json(programSelectList);
//return Json(_context.Program.ToJson());
}
我遗漏了一些基本的东西,毫无疑问,任何帮助都会受到高度赞赏。
感谢。
答案 0 :(得分:1)
从ajax调用返回的响应是一系列项目,每个项目都具有id
和name
属性。因此,当您使用$ .each循环遍历它们时,变量val
将是具有这2个属性的单个js对象。您只需访问这些属性即可设置选项value
和text
。
$.each(data, function (key, val) {
$('#ProgramId').append('<option value="' + val.id + '">' + val.name + '</option>');
});
此外,您可能需要在从GET操作方法返回json数据时指定JsonRequestBehavior
。
return Json(progams,JsonRequestBehavior.AllowGet);