将json字符串作为参数传递给webmethod

我正在将ajax发布到webmethod上EmailFormRequestHandler,我可以在客户端(通过Firebug)看到请求的状态为200,但未达到我的webmethod中的停止点(webmethod的第一行)。json参数一切正常,object但是通过反序列化json的方式,我不得不将其更改为字符串。

js:

function SubmitUserInformation($group) {

var data = ArrayPush($group);

$.ajax({

type: "POST",

url: "http://www.example.com/components/handlers/FormRequestHandler.aspx/EmailFormRequestHandler",

data: JSON.stringify(data), // returns {"to":"bfleming@allegisgroup.com","from":"bfleming@test.com","message":"sdfasdf"}

dataType: 'json',

cache: false,

success: function (msg) {

if (msg) {

$('emailForm-content').hide();

$('emailForm-thankyou').show();

}

},

error: function (msg) {

form.data("validator").invalidate(msg);

}

});

}

aspx:

[WebMethod]

public static bool EmailFormRequestHandler(string json)

{

var serializer = new JavaScriptSerializer(); //stop point set here

serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

dynamic obj = serializer.Deserialize(json, typeof(object));

try

{

MailMessage message = new MailMessage(

new MailAddress(obj.to),

new MailAddress(obj.from)

);

message.Subject = "email test";

message.Body = "email test body" + obj.message;

message.IsBodyHtml = true;

new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]).Send(message);

return true;

}

catch (Exception e)

{

return false;

}

}

回答:

您在jQuery JSON帖子中缺少内容类型:

contentType: "application/json; charset=utf-8",

请参阅本文。当我遇到类似的问题时,它对我很有帮助:

  • 使用jQuery直接调用ASP.NET AJAX页面方法不再可用
  • 来自Internet存档: 使用jQuery直接调用ASP.NET AJAX页面方法

您无需将ScriptManager配置为EnablePageMethods。

另外,您无需在WebMethod中反序列化JSON序列化的对象。让ASP.NET为您做到这一点。将您的WebMethod的签名更改为此(请注意,我在单词“

to”和“ from”后面附加了“

Email”,因为它们是C#关键字,并且不宜使用与关键字相同的名称来命名变量或参数。将需要相应地更改您的JavaScript,以便JSON.stringify()可以正确序列化您的字符串:

// Expected JSON: {"toEmail":"...","fromEmail":"...","message":"..."}

[WebMethod]

public static bool EmailFormRequestHandler(string toEmail, string fromEmail, string message)

{

// TODO: Kill this code...

// var serializer = new JavaScriptSerializer(); //stop point set here

// serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

// dynamic obj = serializer.Deserialize(json, typeof(object));

try

{

var mailMessage = new MailMessage(

new MailAddress(toEmail),

new MailAddress(fromEmail)

);

mailMessage.Subject = "email test";

mailMessage.Body = String.Format("email test body {0}" + message);

mailMessage.IsBodyHtml = true;

new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]).Send(mailMessage);

return true;

}

catch (Exception e)

{

return false;

}

}

以上是 将json字符串作为参数传递给webmethod 的全部内容, 来源链接: utcz.com/qa/417330.html

回到顶部