[英]Reading JSON data returned from ASP.NET MVC
这是我的数据:
[{"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);
}
});
});
你可以这样看
var a = [{ "ServiceId": 4, "ServiceName": "first sevice", "ServiceCriteria": "Lumpsum", "ItemBasis": "Inward/Outward", "Currency": null, "Amount": null}];
alert(a[0].ServiceId);
您的控制器端必须像这样
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);
}
我假设您的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);
}
});
});
我使用以下代码,效果很好:
success: function (data) {
$.each(data, function (index, item) {
alert(data[index].ServiceId)
alert(data[index].ServiceName)
.............................
.............................
//other properties you want to get
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.