我在这里的帖子中搜寻过,但没有找到有效的解决方案...

我正在使用JQuery自动完成功能来显示员工的下拉列表。我可以用值加载列表,但它包含我要传递的字典中的键而不是值。我想同时展示两个。

控制器代码:

public JsonResult GetEmp(string id)
    {
        if (id.Length > 3)
        {
            var result = Json(repository.SearchForEmployee(id), JsonRequestBehavior.AllowGet);
            return result;
        }

        return null;
    }


jQuery代码:

    $('.empId').keyup(function () {
    var x = $('.empId').val();
    var arrayValues = [];
    $.ajax({
        url: '../../Employee/GetEmployee',
        type: "Get",
        data: { id : x },
        cache: false,
        datatype: 'json',
        traditional: true,
        success: function (result) {
            $.each(result, function (item) {
                arrayValues.push(item);
            })
            $(".empId").autocomplete({
            source: arrayValues
        });
        },

        error: function (err) {
            alert('Foo')
        }
    });
});


调试时Controller动作中的JSON结果变量:

[0]  {[12345, Sharon Moore]}
[1]  {[12346, Amy Adams]}
[2]  {[12349, Adam Smith]}


自动完成的JScript数组的实际内容:

12345, 24563, 84565


谁能解释为什么它只引入第一个值(键)?键和值都是字符串。
再次感谢...

最佳答案

由于返回的是对象而不是数组,因此可以尝试如下操作:

var array_of_objects = [];
for (var key in result) {
   var val = result[key];
    //Now you have your key and value which you
    //can add to a collection that your plugin uses
   var obj = {};
   obj.label = key;
   obj.value = val;
   array_of_objects.push(obj);
}

$(".empId").autocomplete({
     source: array_of_objects
});


另外,您也可以在C#代码中返回一个ArrayList(它将是对象/记录的数组)。这是我的一个项目的一些示例代码:

        [HttpPost]
        public ActionResult GetProject(int id) {
            string connStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
            SqlConnection conn = new SqlConnection(connStr);

            string sql = "SELECT * FROM [Portfolio] WHERE [id] = @id";
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            da.SelectCommand.Parameters.Add(new SqlParameter("@id", id));
            DataTable dt = new DataTable();

            conn.Open();
            da.Fill(dt);
            da.Dispose();
            conn.Close();

            return Json(objConv.DataTableToArrayList(dt), JsonRequestBehavior.AllowGet);
        }


objConv是我使用的辅助工具。这是我在上面的代码示例中使用的DataTableToArrayList方法的代码:

public ArrayList DataTableToArrayList(DataTable dataTbl) {

            ArrayList arrList = new ArrayList();

            foreach (DataRow dRow in dataTbl.Rows) {
                Hashtable recordHolder = new Hashtable();
                foreach (DataColumn column in dataTbl.Columns) {
                    if (dRow[column] != System.DBNull.Value) {
                        recordHolder.Add(column.ToString(), dRow[column].ToString());
                    } else {
                        recordHolder.Add(column.ToString(), "");
                    }
                }
                arrList.Add(recordHolder);
            }

            return arrList;
        }

09-26 19:03