2015-02-10 60 views
2

回來時,我需要創建一個循環下面,我已經在那裏的名字將被用於JSON對象和id的值屬性將被用於「姓名」和「身份證」 「數據」和查詢將是我可以設置的一些字符串。 我嘗試使用密鑰對,但無法弄清楚如何做這個屬性。任何幫助,將不勝感激。在MVC創建JSON對象,並從控制器

{ 

    "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/

+1

請不要板着臉回答到的問題。我已刪除並將添加爲維基答案。如果你想回答你自己的問題,讓我知道,我會刪除你打敗我的wiki – Liam 2017-03-17 11:53:24

回答

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); 
+0

,但找出它,所以我會把urs標記爲答案,因爲它接近我必須做的 – Zoinky 2015-02-10 17:56:19

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

備註:不確定方法參數的用途?從OP

1

答:

想通了,下面是代碼

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