[英]using jquery ajax to send a complex object to a webmethod in a aspx page
I'm trying to send a complex object to my WebMethod in a aspx page (asp.net 4.0) using jquery 1.7.1 and json2.js 我正在尝试使用jquery 1.7.1和json2.js将复杂的对象发送到apx页(asp.net 4.0)中的WebMethod
What I have accomplished is to send multiple parameters to a webmethod on the same page and now I want to wrap these parameters in an object instead. 我已经完成的工作是将多个参数发送到同一页面上的web方法,现在我想将这些参数包装在一个对象中。
So my WebMethod looks like this: 所以我的WebMethod看起来像这样:
[WebMethod]
public static string ValidateControlInput(PairValue pair)
{
var result = pair;
return String.Format("Valid");
}
My javascript methods looks like this: 我的javascript方法如下所示:
$(document).ready(ValidateInput);
function ValidatePairInput(codeId, descriptionId, labelId) {
var pair = CreatePairObject(codeId, descriptionId);
SendDataToValidate(pair, labelId);
}
function SendDataToValidate(dataToValidate, controlId) {
$.ajax({
type: 'POST',
url: 'NewDocument.aspx/ValidateControlInput',
contentType: 'application/json; charset=utf-8',
data: dataToValidate,
dataType: 'json',
success: function (data, textStatus) {
var result = data.d;
DisplayValidationMessage(controlId, result);
}
});
}
function DisplayValidationMessage(controlId, result) {
$('#' + controlId).text(result);
}
function CreatePairObject(codeId, descriptionId) {
var pair = { };
pair.Code = $('#' + codeId).val();
pair.Description = $('#' + descriptionId).val();
var DTO = { 'pair': pair };
return JSON.stringify(DTO);
}
Sad to say, this does not work. 可悲的是,这是行不通的。 I set a breakpoint in the webmethod, but that is never hit.
我在web方法中设置了一个断点,但从未实现。
If I replace the code in the javascript method 'CreatePairObject' with this: 如果我将javascript方法“ CreatePairObject”中的代码替换为:
function CreatePairObject(codeId, descriptionId) {
return JSON.stringify({ code: $('#' + codeId).val(), description: $('#' + descriptionId).val() });
}
and the webmethod with this: 和网络方法与此:
[WebMethod]
public static string ValidateControlInput(string code, string description)
{
return String.Format("Valid");
}
it works like a charm. 它就像一个魅力。 So can anyone help me with this?
那么有人可以帮我吗? Any help is much appreciated!
任何帮助深表感谢!
I think your problem is in the CreatePairObject
function, you wrote Code and Description uppercase, and you'r nesting your JSON objects (what arrives to the webmethod is an object with a "pair" attribute containing the pair object). 我认为您的问题出在
CreatePairObject
函数中,您编写的代码和描述是大写的,并且要嵌套JSON对象(到达Web方法的对象是带有“ pair”属性的对象,其中包含pair对象)。 Try to serialize directly the pair object, instead: 尝试直接序列化对对象,而不是:
function CreatePairObject(codeId, descriptionId) {
var pair = { };
pair.code = $('#' + codeId).val();
pair.description = $('#' + descriptionId).val();
return JSON.stringify(pair);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.