Reputation: 2423
There is a dropdown in the page. Changing its value will get related data.
The code works when the type is GET
. When I set it to POST
, the parameter value comes as null. why is it so. How should I make this work even when the type is `POST'.
JS:
$(".ddlBrands").change(function () {
getData("GetModels");
});
function getData(methodName) {
$.ajax({
type:"POST",
url: "/handlers/ModelHandler.ashx",
dataType:"json",
data: { 'methodName': methodName, 'brandId':$(".ddlBrands").val() },
success: function (resultSet) {},
error: function (resultSet) {}
});
}
ASHX:
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/html";
string methodName = context.Request.QueryString["methodName"]; //null when Type is POST
string brandId = context.Request.QueryString["brandId"];
//some more code to get data from DB
}
Upvotes: 2
Views: 1724
Reputation: 832
The query string is the part of the URL after the question mark. For example, in the URL below: http://www.example.com/dosomething?action=stuff¶meter=0
The "query string" is "action=stuff¶meter=0". This holds two variables...
When you set your method to "GET", what actually happens is that jQuery takes your URL and appends a "?" with the parameters after it. For example, if you did the following request:
$.ajax({
type: "GET",
url: "/handlers/ModelHandler.ashx",
dataType: "json",
data: {
"methodName": "run",
"brandId": "3"
},
success: function(resultSet) {},
error: function(resultSet) {}
});
What jQuery will do is tell your browser to "GET" this URL: "/handlers/ModelHandler.ashx?methodName=run&brandId=3". This will allow the ASHX handler to retrieve the "query string", or the part after the "?".
However, when your method is POST, it keeps the same URL, and instead passes the data into the body of the request. Data passed in this way can make use of the "Request.Form[]" property in C#. For example:
string methodName = Request.Form["methodName"];
string brandId = Request.Form["brandId"];
Upvotes: 2
Reputation: 22379
When you send data as part of a POST request, the data does not go into the query string, but rather into the body of the request (a GET request, on the contrary, does not have a body). You're trying to pull "methodName" from the query string as if you were posting to /handlers/ModelHandler.ashx?methodName=blabla
, but it's not there, because this is not the way you're posting.
This might get you the result you need:
methodName = Request.Form["methodName"];
Here are some more examples: Retrieving data from a POST method in ASP.NET
Upvotes: 3