2010-12-09 66 views
0

我使用下面的代碼來生成JSON數據。如何格式化來自ASP.NET MVC的JSON輸出2

[HttpGet] 
    public ActionResult MarketList() 
    { 
     var mkt = db.GetDailyList(); 
     return Json(mkt, JsonRequestBehavior.AllowGet); 
    } 

現在它以下面的格式返回JSON;

[{"gainers":"CAP","date":"Dec 9 ","Open":30.87,"Close":32.41,"change":1.54},{"gainers":"AP","date":"Dec 9 ","Open":20.00,"Close":21.00,"change":1.00}] 

我想要的是以下面的JSON格式返回數據;

[{"dailygainers":{"gainers":"CAP","date":"Dec 9 ","Open":30.87,"Close":32.41,"change":1.54}},{"dailygainers":{"gainers":"AP","date":"Dec 9 ","Open":20.00,"Close":21.00,"change":1.00}}] 

我該如何使用MVC 2做到這一點?

謝謝

+0

no joy gnome ..i將代碼更改爲以下內容,結果相同; public JsonResult TopGainers() { IEnumerable list = db.GetTopGainers(); return Json(list,JsonRequestBehavior.AllowGet); } – femi 2010-12-09 16:51:06

回答

0

將操作更改爲JsonResult。我使用了過去使用的這段代碼。請記住,我用它來動態填充下拉列表。

的HomeController

[HttpGet] 
public JsonResult GetSubjects(string term) 
{ 
    IEnumerable<Textbook> subjects = _repository.GetSubjects(term); 
    return Json(subjects, JsonRequestBehavior.AllowGet); 
} 

查看

<p> 
<label for="Subject">Subject</label> 
<select name="Subject" id="Subject"></select> 
</p> 

jQuery的

$("#Term").change(function() { 
    var term = $("#Term > option:selected").attr("value"); 
    var items = "<option>Select</option>"; 
    $.getJSON(host + "/Home/GetSubjects/" + term, function (data) { 
     $.each(data, function (i, d) { 
      items += "<option value='" + d.Subject + "'>" + d.Subject + "</option>"; 
     }); 
     $("#Subject").html(items); 
    }); 
}); 
+0

謝謝,但沒有幫助...我改變了代碼使用JsonResult,但它仍然給出了相同的輸出..我注意到的事情是每個JSON條目在它前面有'dailygainers'..好像是主要區別..在哪裏我得到說明在代碼中?謝謝 – femi 2010-12-09 16:10:12

1

但對於其他人誰在這個問題上絆倒我必須做同樣的事情,我用的LINQ做。

因此,您將新var命名爲容器的名稱,它應該這樣做!

var formatedList = (new {dailygainers = db.GetDailyList()});