从c#返回Json格式响应

时间:2015-07-03 08:38:30

标签: c# ajax json asp.net-mvc

我需要关注来自ajax调用的json响应:

[{url:"http://localhost:63220/Images/heroAccent.png"},
{url:"http://localhost:63220/Images/heroAccent.png"}]

我的ajax电话是:

function loadtest() {
    $.ajax({
        type: 'GET',
        url: '/Home/TestMethod',
        async: true,
        dataType:'json',
        cache: false,
        error: function () {
            alert('Errror');
        },
        success: function (data) {
            console.log(data);
        }
    });
}

我的控制器是:

public JsonResult TestMethod()
    {
        var items = new[] {
                            new {url = "http://localhost:63220/Images/heroAccent.png"}, 
                            new {url = "http://localhost:63220/Images/heroAccent.png"} };

        return Json(items, JsonRequestBehavior.AllowGet);
    }

它提供响应:

    [{"url":"http://localhost:63220/Images/heroAccent.png"},
    {"url":"http://localhost:63220/Images/heroAccent.png"}]

但我需要以下回复。我怎么能得到它?

[{url:"http://localhost:63220/Images/heroAccent.png"},
{url:"http://localhost:63220/Images/heroAccent.png"}]

2 个答案:

答案 0 :(得分:1)

您将以JSON格式获得所需的响应。要将其转换为对象,请使用:

JSON.parse(data);

答案 1 :(得分:-1)

您可以使用课程。

 var items = new List<Item>() { new Item() { url = "http://www.google.com" }, new Item() { url = "http://www.youtube.com" } };
 return Json(items, JsonRequestBehavior.AllowGet);

<强>类

 public class Item
    {
        public string Url { get; set; }
    }

<强>结果

enter image description here