使用ajax调用返回JSON对象的mvc控制器在razor视图中构建选择列表时出现问题

时间:2016-11-04 14:48:28

标签: jquery json ajax asp.net-mvc razor

正如标题所说,我在这方面遇到了一些麻烦。我成功地对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);
    }

目前的结果 It is not handling the returned object

当前对象 Object looks ok

这种硬编码适用于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());
    }

我遗漏了一些基本的东西,毫无疑问,任何帮助都会受到高度赞赏。

感谢。

1 个答案:

答案 0 :(得分:1)

从ajax调用返回的响应是一系列项目,每个项目都具有idname属性。因此,当您使用$ .each循环遍历它们时,变量val将是具有这2个属性的单个js对象。您只需访问这些属性即可设置选项valuetext

$.each(data, function (key, val) {
    $('#ProgramId').append('<option value="' + val.id + '">' + val.name + '</option>');
});

此外,您可能需要在从GET操作方法返回json数据时指定JsonRequestBehavior

return Json(progams,JsonRequestBehavior.AllowGet);