【问题标题】:Parse key/value pair from JSON dictionary result in MVC从 JSON 字典结果中解析键/值对到 MVC
【发布时间】:2014-01-10 17:50:07
【问题描述】:

我已经浏览了这里的帖子,但没有找到可行的解决方案...

我正在为员工的下拉列表使用 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

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

【问题讨论】:

  • 您的值字符串是否需要引号?
  • 当您在console.log(result) 回调中看到什么?
  • 控制台。日志结果是:{"1289":"KIRK BELL","1827":"LINDA JONES","1963":"LINDA SMITH"}
  • 这看起来像一个对象,而不是一个数组或对象数组。

标签: javascript jquery asp.net-mvc json dictionary


【解决方案1】:

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

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;
        }

【讨论】:

    【解决方案2】:

    JQuery UI Autocomplete 需要特定的数据结构才能工作。

    SearchForEmployee 必须返回此格式的数据列表:

    public class EmployeeAutocomplete
    {
       public string @label { get; set; }
       public string @value { get; set; }
    }
    

    或者您需要在 javascript 中转换为该格式而不是数组列表:

    success: function (result) {
            $.each(result, function (item) {
                arrayValues.push(new { label: item[1], value: item[0] });
            });
            $(".empId").autocomplete({
                source: arrayValues
            });
        },
    

    自动完成参考:http://api.jqueryui.com/autocomplete/

    【讨论】:

      【解决方案3】:

      jQuery UI Autocomplete 可以自己进行 ajax 调用,所以我真的不明白你为什么要单独进行 ajax 调用。

      $("#txtbox").autocomplete({
          source: url
      });
      

      尽管如此,如果您想返回值和标签,则控制器中的 json 应该以[ { label: "Choice1", value: "value1" }, ... ] 的格式返回。

      http://api.jqueryui.com/autocomplete/#option-source

      【讨论】:

      • 结果返回为 {"1289":"KIRK BELL","1827":"LINDA JONES","1963":"LINDA SMITH"} 。如何将它们转换为格式: [ { label: "Choice1", value: "value1" }, ... ]
      • 这是一个大对象,而不是 jquery ui autocompelete 期望的对象数组。乍一看,不用深入c#代码,只需要返回一个序列化成json的c#列表对象
      【解决方案4】:

      这是我在几个地方使用的一段代码。我没有使用您正在使用的自动完成功能,但我认为这不是问题。

      客户端:

          $.getJSON('../../Employee/GetEmployee', { id: x }, function (results) {
              var yourDropdown = $('#YourDropdown');
              var json = JSON.parse(results);
              $.each(json, function (index, item) {
                  yourDropdown.append($('<option/>', {
                      value: item.Value,
                      text: item.Text
                  }));
              });
      
              //Implement the autocomplete feature.
          });
      

      服务器端:

          [HttpGet]
          public JsonResult GetElements(int id)
          {
              IEnumerable<SelectListItem> elements;
      
              //Some routine that gets the elements goes here.
      
              var serializer = new JavaScriptSerializer();
              return Json(serializer.Serialize(elements), JsonRequestBehavior.AllowGet);
          }
      

      我没有在您的特定场景中测试过代码,但它应该可以工作,因为我在多个地方使用了代码 sn-p。

      注意:尝试使用 getJson 方法而不是 $.ajax。它是您正在使用的 ajax 实现的快捷方式。如您所见,代码不那么冗长且更具可读性。

      【讨论】:

        猜你喜欢
        • 2017-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        • 2018-09-11
        相关资源
        最近更新 更多