Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing json string as parameter to webmethod

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 hitting the stop point (first line of the webmethod) in my webmethod. Everything was working fine with the json param was an object but with the way that I'm deserializing the json I had to change it to a string.

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":"[email protected]","from":"[email protected]","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;
    }
}
like image 854
bflemi3 Avatar asked Mar 15 '26 11:03

bflemi3


1 Answers

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;
    }
}
like image 187
Mario J Vargas Avatar answered Mar 18 '26 00:03

Mario J Vargas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!