J'utilise la valeur Data comme littéral d'objet, au lieu de concaténer une chaîne comme expliqué dans cette réponse
Mon code est le suivant:
$.ajax({
url: "../Member/Home.aspx/SaveClient",
type: "POST",
async: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
"projectSoid": ProjectId,
"startDate": StartDate,
"endDate": EndDate,
"clientManager": ClientManager
},
success: function(response) {
if (response.d != "") {
}
},
error: function(response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
})
et ma méthode web est comme ceci:
[WebMethod]
public static string SaveClient(string projectSoid, string startDate,
string endDate, string clientManager)
{
...
}
Mais j'obtiens l'erreur suivante:
Message: primitive JSON non valide: projectSoid
Avec votre contentType: 'application/json; charset=utf-8'
vous prétendez que vous enverrez JSON mais actuellement votre propriété data
ne contient pas JSON.
Vous devez transformer votre data
en JSON avec le JSON.stringify
méthode:
Modifiez donc votre propriété data
en:
data: JSON.stringify({
"projectSoid": ProjectId,
"startDate": StartDate,
"endDate": EndDate,
"clientManager": ClientManager
}),
Vous devez noter que le JSON.stringify
La méthode n'est pas prise en charge nativement dans les anciens navigateurs, vous devrez donc peut-être fournir une implémentation en utilisant l'une des différentes bibliothèques comme:
Douglas Crockford's bibliothèque JSON2.
Javascript côté client
var items = [{ projectSoid: ProjectId, startDate: StartDate, endDate: EndDate, clientManager: ClientManager }];
$.ajax({
url: '"../Member/Home.aspx/SaveClient',
type: "POST",
data: JSON.stringify({ items: items }),
//data: JSON.stringify("{DocKey : '" + DocKey + "',highlightText: '" + JSON.stringify(text) + "',pageNo: '" + pgNo + "',left: '" + left + "',top: '" + top + "',width: '" + width + "',height: '" + height + "'}"),
//data: "{DocKey\":\""+ DocKey+"\",\"highlightText\":\""+ text +"\",\"pageNo\":\""+pgNo+"\",\"left\":\""+left+"\",\"top\":\""+top+",\"width\":\""+width+"\",\"height\":\""+ height +"}}",
// data: "{DocKey : '" + DocKey + "',highlightText: '" + text + "',pageNo: '" + pgNo + "',left: '" + left + "',top: '" + top + "',width: '" + width + "',height: '" + height + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("Save data Successfully");
},
failure: function (msg) { alert("Sorry!!! "); evt.obj.deleteObject(); },
async: false
});
Méthode Web au code derrière
[WebMethod]
public static string SaveClient(object items) {
List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
Dictionary<string, object> dic = (Dictionary<string, object>)lstItems[0];
}