读取ASP.NET MVC返回的JSON数据

时间:2014-02-27 07:59:15

标签: jquery asp.net asp.net-mvc asp.net-mvc-3

这是我的数据:

[{"ServiceId":4,"ServiceName":"first sevice","ServiceCriteria":"Lumpsum","ItemBasis":"Inward/Outward","Currency":null,"Amount":null}]

如果成功从控制器传回数据,我该如何阅读?

  $('#btnservice').click(function () {
        var url = "/Quotation/SelectService/";
        var selservice = $("#selservice").val();
        $.ajax({
            url: url,
            data: { selservice: selservice },
            cache: false,               
            dataType: 'json',
            type: "POST",
            success: function (data) {               

                $("#Services").empty();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });
    });

4 个答案:

答案 0 :(得分:1)

你可以这样阅读

 var a = [{ "ServiceId": 4, "ServiceName": "first sevice", "ServiceCriteria": "Lumpsum", "ItemBasis": "Inward/Outward", "Currency": null, "Amount": null}];
        alert(a[0].ServiceId);

答案 1 :(得分:0)

你的控制器端必须是这样的

public string SelectService(string ServiceId, string ServiceName, string ServiceCriteria, string ItemBasis, string Currency, string Amount)
{
    string message = string.Empty;
    //do whatever you want here and return message like 
    message=success;
    return message;
}

在视图页面中检查返回值是否成功。

    success: function (data) {               
         if(data=="success" )
         {
            //to do
            $("#Services").empty();
         }
         else
         { 
            //bla bla
         }
   },
   error: function (reponse) {
   alert("error : " + reponse);
   }

答案 2 :(得分:0)

我假设控制器返回了您的JSON字符串。您可以访问success回调中的返回数据。您的data变量已包含此回复。

$('#btnservice').click(function () {
    var url = "/Quotation/SelectService/";
    var selservice = $("#selservice").val();

    $.ajax({
        url: url,
        data: { selservice: selservice },
        cache: false,               
        dataType: 'json',
        type: "POST",
        success: function (data) {               
            var service = data[0];

            alert(service.ServiceName); // Should be "first service"

            $("#Services").empty();
        },
        error: function (reponse) {
            alert("error : " + reponse);
        }
    });
});

答案 3 :(得分:0)

我使用以下代码并且效果很好:

success: function (data) {
     $.each(data, function (index, item) {
     alert(data[index].ServiceId)
     alert(data[index].ServiceName)    
     .............................
     .............................
     //other properties you want to get                      
     });
    }