Parameter to Web Service via Jquery Ajax Call

1.7k Views Asked by At

I am using revealing module pattern and knockout to bind a form. When data is entered in that form(registration), it needs to be posted back to MVC4 web method.

Here is the Jquery code

    /*
Requires JQuery
Requires Knockout
*/
op.TestCall = function () {

    // Private Area
    var _tmpl = { load: "Loading", form: "RegisterForm"};

    var
    title = ko.observable(null)
    template = ko.observable(_tmpl.load),
    msg = ko.observable(),

    postData = ko.observable(),

    PostRegistration = function () {
        console.log("Ajax Call Start");
        var test = GetPostData();
        $.ajax({

            type: "POST",
            url: obj.postURL, //Your URL here api/registration
            data: GetPostData(),
            dataType: "json",
            traditional: true,
            contentType: 'application/json; charset=utf-8'


        }).done(Success).fail(Failure);
        console.log("Ajax Call End");
    },
    GetPostData = function () {
        var postData = JSON.stringify({
            dummyText1: dummyText1(),
            dummyText2: dummyText2(),

        });
        return postData;

    }


    return {
        // Public Area
        title: title,
        template: template,
        dummyText1: dummyText1,
        dummyText2: dummyText2
    };
}();

The controller code is simple as per now

 // POST api/registration
    public void Post(string data)
    {

        ///TODO

    }

When i am trying to, capture the data (using simple console.log) and validate it in jslint.com, it's a valid Json.

  1. I tried hardcoding the data as

    data: "{data: '{\'name\':\'niall\'}'}", But still i get as null, in my web method.

  2. Added the tag [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] to my Post method in controlled, but still no fruitful result

  3. Even tried JSON.Stringify data: JSON.stringify(data) but still i get null in my web-method.

I am not able to figure out the solution.

Similar issue was found @ this link http://forums.asp.net/t/1555940.aspx/1 even Passing parameter to WebMethod with jQuery Ajax but didn't help me :(

2

There are 2 best solutions below

0
On

Only escaped double-quote characters are allowed, not single-quotes, so you just have to replace single quotes with double quotes:

data: "{data: '{\"name\":\"niall\"}'}"

Or if you want to use the stringify function you can use it this way:

data: "{data: '" + JSON.stringify(data) + "'}"
1
On

MVC and WebApi uses the concept of Model Binding.

So the easiest solution is that you need to create a Model class which matches the structure of the sent Json data to accept the data on the server:

public void Post(MyModel model)
{
   ///TODO
}

public class MyModel
{
   public string DummyText1 { get; set; }

   public string DummyText1 { get; set; }
}

Note: The json and C# property names should match.