简体   繁体   中英

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

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

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.

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 addd 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM