开发者

how to format JSON output from ASP.NET MVC 2

开发者 https://www.devze.com 2023-01-29 12:04 出处:网络
i used the code below to generate JSON Data. [HttpGet] public ActionResult MarketList() { var mkt = db.GetDailyList();

i used the code below to generate JSON Data.

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

Now it returns JSON in the format below;

[{"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}]

what i want is to return data in the following JSON Format;

[{"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}}]

How can i do this using MVC 2 开发者_如何学编程please?

Thanks


but for anyone else who stumbles on this problem I had to do something similar and I used Linq to do it.

So you name the new var the name of the container and it should do it!

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


Change Action to JsonResult. I use this snippet of what I've used in the past. Keep in mind I used this to dynamically populate a drop down list.

HomeController

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

View

<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

精彩评论

暂无评论...
验证码 换一张
取 消