选择二;如何加载我从数据库加载一次的数组

时间:2015-08-07 19:57:42

标签: javascript arrays asp.net-mvc callback jquery-select2

我正在使用以下Action的结果加载数组:

img.behind {
z-index: 0;
position: relative;
left: 20px;
top: 40px;
}

我正在尝试将此数组加载到Select2元素中,并且没有成功。 select2元素始终为空。这是我用来加载select2的javascript:

public ActionResult GetJudges(string q)
    {
        var judges = new List<Judge>();
        using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
        {
            using (var cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "query";
                con.Open();
                using (var rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        var judge = default(Judge);
                        var id = Convert.ToInt32(rdr["ID"]);
                        var email = Convert.ToString(rdr["Email"]);
                        var name = Convert.ToString(rdr["Name"]);
                        var jurisdiction = Convert.ToString(rdr["Jurisdiction"]);
                        var code= Convert.ToString(rdr["code"]);

                        if (!judges.Select(x => x.Id).Contains(id))
                        {
                            judge = new Judge
                            {
                                Id = id,
                                Email = email,
                                Name = name,
                                Code= code
                            };
                            judges.Add(judge);
                        }
                        else
                        {
                            judge = judges.FirstOrDefault(x => x.id == id);
                        }

                        judge.Jurisdictions.Add(jurisdiction);
                    }
                }
                con.Close();
            }
        }
        return Json(judges, JsonRequestBehavior.AllowGet);
    }

谁能告诉我这里缺少什么?

1 个答案:

答案 0 :(得分:0)

查看有关如何使用select2的this示例。您传输的数据不正确。您的result应该包含一个具有id属性和text属性的对象数组,您应该直接将它作为data传递给select2,而不是将其包装在另一个对象中。

//sample data
var result = [{id: 0, text: 'Judge 1'}, {id: 1, text: 'Judge 2'}];

$(".select2").select2({
    placeholder: "Search for a Judge",
    data: result
});