在 mvc 中创建 json 对象并从控制器返回

Zoi*_*nky 3 asp.net-mvc json

我需要在循环中创建以下内容,我有“name”和“id”,其中 name 将用于 json 对象的 value 属性,id 将用于“data”,查询将是一些字符串我可以放。我尝试使用密钥对,但无法弄清楚如何执行此属性。任何帮助,将不胜感激。

{

    "query": "Unit",
    "suggestions": [
        { "value": "United Arab Emirates", "data": "AE" },
        { "value": "United Kingdom",       "data": "UK" },
        { "value": "United States",        "data": "US" }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试返回此自动完成小部件的结果 https://www.devbridge.com/sourcery/components/jquery-autocomplete/

小智 6

You can just create an anonymous object. To return the JSON as indicated in your question, it would be

public JsonResult GetCities(string query)
{
  var data = new
  {
    query = "Unit",
    suggestions = new[]
    {
      new { value = "United Arab Emirates", data = "AE" },
      new { value = "United Kingdom", data = "UK" },
      new { value = "United States", data = "US" }
    }
  };
  return Json(data, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

Side note: Unsure of the purpose of the method parameter?