Sana Joseph
Sana Joseph

Reputation: 1948

Read Post Data With C#

I'm Using the Jquery Ajax Function to send data from an html page, & I'm reading it at the backend with C#.

When I used Get, the data were sent successfully, but when I switched to Post, the data value is null at the backend.

HTML:

<form onsubmit="AddData();>
<input type="submit"value="Submit" />
</form>

Javascript:

function AddData() {
            var RData = GetRData();
            var postData = { 'Function': "AddData", 'RData': JSON.stringify(RData) };
            $.ajax(
            {
                type: "POST",
                url: "/Services/GetRData.aspx",
                data: postData,
                contentType: "application/json; charset=utf-8",
                dataType: "jsonp",
                jsonp: 'jsoncallback',
                success: function (result) { 
                AddClubCallBackFunction(result) },
                error: function (msg) {
                    alert('Sorry, an error occured while adding your Data!');
                }
            });
        }

C#:

string FunctionName =Request["Function"]; //null
string RData = Request.Form["RData"]; //null

So, what am I doing wrong & how can I fix it ?

Update:

I just removed

contentType: "application/json; charset=utf-8",

and it worked.

Upvotes: 3

Views: 4015

Answers (1)

James
James

Reputation: 82096

Assuming the above code is exactly what you are executing, there does appear to be a typo:

var Data = GetRData();
var postData = { 'Function': "AddData", 'RData': JSON.stringify(RData) };

Your variable is Data but your calling JSON.Stringify on RData which hasn't been declared (hence null property).

Update

Based on your last comment I would say it's a JSON formatting issue. This can generally happen when you attempt to manually construct JSON objects which you are partly doing in your solution. I would change your code to:

var rdata = GetRData();
var postData = { Function: 'AddData', RData: JSON.stringify(rdata) };
$.ajax({
    ...
    data: JSON.stringify(postData),
    ...
});

Upvotes: 1

Related Questions