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;
}
}
You mean you want to set a break point? Don't set that point in firebug. Set that breakpoint in VS itself. Then attach VS to local IIS.
By the way, in your ajax call you set three parameter, your webmethod takes only one. and the parameter name must be the same.
The format of your data attribute in the ajax call is also not good. It should look like this
data: '{"to":"bfleming@allegisgroup.com","from":"bfleming@test.com","message":"sdfasdf"}',
it should be framed in ' '
First thing I noticed is that you are missing contentType: "application/json; charset=utf-8" in your $.ajax. Also affffd to your $.ajax a complete callback it returns jqXHR,textStatus. I think the complete callback will help because textStatus one of the following ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). This might help you track down the issue.
May be this code helps someone:
public Dictionary<string, object> JsonToDictionary(dynamic request)
{
JObject x = JObject.FromObject(request);
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (JProperty prop in (JContainer)x)
{
result.Add(prop.Name, prop.Value);
}
return result;
}
I use it while debuging when frontend comes first.