Shane LeBlanc
Shane LeBlanc

Reputation: 2643

Using jQuery $.Ajax to pass a DTO to a WebMethod along with an additional parameter

Good day,

I've got WebMethod that looks a bit like this...

[WebMethod]
    public static string ProcessItem(Item item, ItemStatus status)
    {
        try
        {
            item.Process(status);
            return "Success!";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

And I've got an jQuery method that looks a bit like this...

function Process(dto, status) {
        $.ajax({
            type: 'POST',
            url: 'ProcessPO.aspx/ProcessItem',
            data: JSON.stringify(dto) + status',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (msg) {
                if (msg.d)
                    alert('success');
            },
            error: function (xhr, status, errorThrown) {
                alert(xhr.responseText);
            }
        });
    }

In the data: line, how do I concatenate the two so they're passed in properly?

The dto is defined like this...

var dto = { 'item': item };

Upvotes: 3

Views: 2349

Answers (1)

Rob
Rob

Reputation: 1081

var d = JSON.Stringify(dto);
d.status = status;

Then in the ajax call

data: d

Also by looking at your code you may want to return a JsonResult.

return Json(new {Success=true}); //Success
return Json(new {Success=false, Message = ex.Message}); //Failure

//if it is a get request
return Json(new {Success=true}, JsonRequestBehavior.AllowGet) //Success
return Json(new {Success=false, Message = ex.Message}, JsonRequestBehavior.AllowGet) //Failure

This will allow you to see the result of the method in the javascript.

success: function(response){
    if(response.Success){
        alert('Success!');
    }else{
        alert('Failure! ' + response.Message);
    }
}

Upvotes: 3

Related Questions