ZP Baloch
ZP Baloch

Reputation: 391

$.post is not send data to web form

Function:

$.post("/SurveyResult.aspx", {
    test: 'testing',
}).done(function (data) {
    alert("Data Updated");
});

ServerSide of :

 protected void Page_Load(object sender, EventArgs e)
 {    
    var formValue = Request.Form["test"];
 }

function is posting well But I'm getting null value of test at server side. Do not know what the issue is.

Upvotes: 1

Views: 386

Answers (3)

Igor
Igor

Reputation: 62238

You are currently not posting form encoded data but a json string. If you want to keep the aspx as the end point and access the variables using the Form collection then you will have to change your ajax call to post form encoded data and specify that in the header of the http call.

$.post({
    url: "/SurveyResult.aspx",
    data: $.param({test: 'testing'}),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).done(function (data) {
  alert("Data Updated");
});

See also param which makes passing / transforming objects as a part of the request data a little easier to write. You could also replace it with this hard coded string.

data: "test=testing",

Upvotes: 0

Sudipto
Sudipto

Reputation: 41

You will need to mark the method on the aspx code behind as a webmethod and specify the same when you are posting to it.On the client, you will need to make the following change:

$.post("/SurveyResult.aspx/OnSubmit", {
test: 'testing',
}).done(function (data) {
alert("Data Updated");
});

Also, in your code-behind you will need to expose the method you want to be called to handle the post.

[WebMethod]
public static string OnSubmit(string test)
{
   var value = test;

}

Upvotes: 0

Amr Elgarhy
Amr Elgarhy

Reputation: 69002

You will need a web method on the server side to receive this ajax call, it can't be done on the page load since this should be an ajax call not a full page refresh.

To know more about web methods:
Using jQuery for AJAX with ASP.NET Webforms
Calling a webmethod with jquery in asp.net webforms

And personally I used to use services with ajax instead of page methods in asp.net forms : https://channel9.msdn.com/Blogs/ASP-NET-Site-Videos/how-do-i-make-ajax-calls-using-jquery

Upvotes: 1

Related Questions