I\'m making an ajax post to a webmethod EmailFormRequestHandler
, I can see on the client side (through firebug) that status of the request is 200 but it\'s not hit
You're missing the content type in the jQuery JSON post:
contentType: "application/json; charset=utf-8",
See this article. It helped me greatly when I had a similar issue:
You don't need to configure the ScriptManager to EnablePageMethods.
Also, you don't need to deserialize the JSON-serialized object in your WebMethod. Let ASP.NET do that for you. Change the signature of your WebMethod to this (noticed that I appended "Email" to the words "to" and "from" because these are C# keywords and it's a bad practice to name variables or parameters that are the same as a keyword. You will need to change your JavaScript accordingly so the JSON.stringify() will serialize your string correctly:
// 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;
}
}