我正在使用AJAX将JSON数组传递给.NET Web服务。 Stringified JSON数组在发送时是正确的 - 我在JS警报中显示内容 - 但是当我在Web服务中输出它时,它只显示空值。
帮助。
JS是这样的:
var listitems = [];
$('#job-item-list').children('.iamalistitem').each(function () {
listitems.push({ "title": $(this).find('.job-item-title').text(), "price": $(this).find('.job-item-price').text().replace("£","").replace("£","") });
});
alert(JSON.stringify({ ListItems: listitems }));
$.ajax({
type: "POST",
url: "/ld_jobs.asmx/putJobItems",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ ListItems : listitems }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var responseObjTwo = JSON.parse(response.d);
//showUserMessage(responseObjTwo.Message, false);
showUserMessage(response.d, false);
},
error: function (response) {
var responseObj = JSON.parse(response.responseText);
showUserMessage(responseObj.Message, true);
}
});
接收服务是:
public class ListItem
{
public string itemTitle { get; set; }
public decimal itemPrice { get; set; }
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string putJobItems(ListItem[] ListItems)
{
// Add to DB
int errorNumber = 0;
try
{
// check if on DB already
string returnstring = "";
errorNumber++; //1
foreach (ListItem item in ListItems)
{
errorNumber++; //2,3,4
returnstring += "Desc: " + item.itemTitle + "; Price: " + item.itemPrice.ToString() + "; ";
}
errorNumber++; //5
return "{ \"Status\" : \"Success\", \"Message\" : \"Your request has been successfully posted. Well done you. Go put the kettle on and be lazy! \", \"input\" : \"" + returnstring + ": " + errorNumber.ToString() + "\" }";
}
catch (Exception ex)
{
Exception newEx = new Exception("Well this is quite embarassing. It seems the badgers have escaped! (Actual error: " + ex.Message + "; error: " + errorNumber.ToString() + ")");
throw newEx;
}
}
进入的Stringyfied字段是:
{"ListItems":[{"title":"(Groceries) 4 pints of milk","price":"2.00"},{"title":"(Groceries) 2 loafs of bread","price":"3.00"},{"title":"(Subway) Foot Long BMT","price":"3.00"}]}
Response.d返回:
{ "Status" : "Success", "Message" : "Your request has been successfully posted. Well done you. Go put the kettle on and be lazy! ", "input" : "Desc: ; Price: 0; Desc: ; Price: 0; Desc: ; Price: 0; : 5" }
任何帮助非常感谢。感谢。
答案 0 :(得分:1)
您在客户端上使用title
和price
属性名称,但在服务器上使用itemTitle
和itemPrice
。调整它们以使用相同的名称。