passing json string as parameter to webmethod

后端 未结 4 686
野性不改
野性不改 2021-01-21 00:29

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

4条回答
  •  生来不讨喜
    2021-01-21 01:06

    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:

    • Using jQuery to directly call ASP.NET AJAX page methods (no longer available)
    • From Internet Archive: Using jQuery to directly call ASP.NET AJAX page methods

    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;
        }
    }
    

提交回复
热议问题