我需要在循环中创建以下内容,我有“name”和“id”,其中name将用于json对象的value属性,id将用于“data”,查询将是一些我可以设置的字符串。 我尝试使用keypair,但无法弄清楚如何做这个属性。任何帮助将不胜感激。
{
"query": "Unit",
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
我正在尝试返回此自动完成小部件的结果 https://www.devbridge.com/sourcery/components/jquery-autocomplete/
答案 0 :(得分:4)
我讨厌全力以赴,但也许可以创建自己的课程?
public class DataValuePair
{
public string Data {get;set;}
public string Value {get;set;}
}
public class SearchResult
{
public string Query {get;set;}
public List<DataValuePair> Suggestions {get;set;}
}
现在您可以返回JSON结果
return Json(mySearchResult);
答案 1 :(得分:3)
您只需创建一个匿名对象即可。要按照问题中的说明返回JSON,它将是
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);
}
附注:不确定方法参数的用途?
答案 2 :(得分:1)
来自OP的答案:
想出来,下面是代码
public ActionResult GetCities(string query)
{
var obj = new CitySuggestion();
obj.suggestions.Add(new Suggestion { value = "test1", data = "test1" });
obj.suggestions.Add(new Suggestion { value = "test2", data = "test2" });
obj.suggestions.Add(new Suggestion { value = "test3", data = "test3" });
return Content(JsonConvert.SerializeObject(obj), "application/json");
}
public class CitySuggestion
{
public CitySuggestion()
{
suggestions = new List<Suggestion>();
}
public List<Suggestion> suggestions
{
get;
set;
}
}
public class Suggestion
{
public string value { get; set; }
public string data { get; set; }
}