How to get post data as json in asp.net? - asp.net

I am making an ajax request to my API but my API expects raw json data to parse its own objects in C# how do I get the raw Json data in C#? from the "HttpContext.Current.Request"
Here is my request:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
contentType: "Application/JSON",
data: {
code: "login",
data: {
username: $("#login_username").val(),
password: $("#login_password").val(),
rememberMe: $("#rememberMe").val()
}
},
success: function (result) {
},
error: function (result) {
console.log(result);
}
});

You should be able to get body of the request using property 'HttpRequest.InputStream`. The type of the property is a stream, but you can see an example on MSDN on how to convert it to string.
Depending of what is your underlying framework there can be easier ways to get the body. E.g. MVC of Web API use binding to map incoming requests to objects, so it might be an option to consider.

Related

jquery-ajax post values to http-generic-handler don't return anything

I have a generic-http-handler and I am calling it from jQuery.
My handler only insert values in database but does not return anything.
I am calling the handler as follow
function InsertAnswerLog(url) {
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: { 'Url': url, 'LogType': "logtype" },
success: function (data) {
},
error: function (Error) {
}
});
}
Everything is working fine for me.
But is it the best way to post the values to the server.
Or can I use it in a better way.
it seems the type of data you are sending is JSON encoded try serializing the data in this form before sending and then on the server side you should encode the data before sending it back.
serializing before sending to server
function InsertAnswerLog(url) {
var DatatoSend = { 'Url': url, 'LogType': "logtype" } ;
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: {Jsondata: JSON.stringify(DatatoSend)},
success: function (data) {
},
error: function (Error) {
}
});
}
now on the sever side scipt
// NB: i use PHP not asp.net but it think it should be something like
Json.decode(Jsondata);
// do what you want to do with the data
// to send response back to page
Json.encode(Resonponse);
// then you could in php echo or equivalent in asp send out the data
It is important that you decode the json data on the server-side script and when a response is to be sent it should be encoded back it JSON form for it to be understood as a returned json data.
I hope this helps.

How to get remote JSON to work with Kendo grid in ASP.NET

I can successfully make the AJAX call to my service with the following code:
var serverData = { "ZoneParent": "123" };
var request = $.ajax({
type: "POST",
url: "/./Services/Reports.svc/getZones",
contentType: "application/json",
dataType: "json",
jsonp: null,
jsonpCallback: null,
data: JSON.stringify(serverData)
});
request.done(function (msg) {
alert(JSON.stringify(msg));
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
However, when I try to implement the same call with my Kendo grid I get an error
The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'
for getZones. My service call work fine with DataTables, but I want to switch to Kendo potentially. I have messed with this for days to no avail. The application is not MVC. Here is my Kendo code snippet:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/./Services/Reports.svc/getZones",
dataType: "JSON",
data: { zoneParent: "123" },
type: "POST"
},
parameterMap: function (data, operation) {
return kendo.stringify(data);
}
},
schema: {
data: "d"
}
});
var grid = $("#allGrids").kendoGrid({
dataSource: dataSource,
height: 200
});
As cfeduke made similar suggestion you can try to add contentType to the read object of the transport read config just as you did in the $.ajax call.
e.g.
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/./Services/Reports.svc/getZones",
dataType: "json",
contentType: "application/json",
data: { zoneParent: "123" },
type: "POST"
},
parameterMap: function (data, operation) {
return kendo.stringify(data);
}
},
It sounds like the server's reply "Content-type" header is something other than the expected "application/json".
You can use cURL:
curl -v -H "Content-type:application/json" -H "Accept:application/json" \
http://localhost/Services/Reports.svc/getZones
to invoke the endpoint and check the returned header values (-v is verbose, you won't see the headers without it).
Sometimes just setting an "Accept: application/json" header is enough to reveal the problem - either the server coerces the output into JSON or it throws an error that can be tracked down.
I am investigating if there is a another way around this. But seems like Kendo has many limitations and this is one of them. Datables doesn't need a header, just the JSON format.
This is what you need to add to your controller that is sending the data (in case its ajax call)
header("Content-type: application/json");
I wish it wouldn't be like this but Kendo forces this I believe. I prefer datatables, much more freedom and you can customize more.

Send JSON data to ASP.NET HTTP Handler

i have an ASP.NET 4.0 HTTP handler that should receive and send data in json format. I'm using jquery to send json objects serialized in a string to the handler. It correctly sends the request but i don't know how i could retrieve the data from the httpcontext passed to the handler and how i could deserialize it... Can someone help me?
UPDATE 1
$.ajax({
type: "POST",
url: "myurl.ashx",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: $.toJSON({
...
}),
success: function (response) {
...
}
});
Do you send the data from jquery as a POST or GET request? In your Http Handler you can retrieve the values through the HttpContext.Request either via Forms or QueryString
ie. string json = HttpContext.Current.Request.Forms["json"];
To deserialize you can use the built in System.Web.Script.Serialization.JavaScriptSerializer class like this
string json = HttpContext.Current.Request.Forms["json"];
var js = new JavaScriptSerializer();
YourType obj = js.Deserialize<YourType>(json);

How to pass parameter back from asp.net web service if an insert to a database was successful? ASP.NET/jQuery/AJAX/JSON

I have a web form and I use jQuery/AJAX/JSON to send objects to a web service using:
$.ajax({
type: "POST",
url: "SynchroniseCustomers.asmx/synchroniseCustomers",
data: JSON.stringify(customerObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status) {},
success: function (msg) {}
});
From the web service I want to check if the insert into the database was successfull, return a variable with an ID and pass this ID to a function. In the object I have the ID so I could have:
success: function (msg) {deleteCustomer(ID);}
But this only checks if the data was passed to my method in the web service?
I have followed this example
http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/
and in the class Person I get a message back from the database server telling me if the insert was successfull or not so like:
if (successfull)
{
return ID;
}
Is there a way to get this ID back to the web form and use this in a variable?
Thanks in advance.
You want to return a result object with an isSuccess and id property. You can then do the following:
success: function (result) {
if (!result.isSuccess) {
// display friendly error message indicating that the db insert failed
} else {
var id = result.id;
// do client side processing with primary key returned from db insert
}
}
How you return the result object depends on your web services framework (e.g., WCF, MVC, WebMethod, etc.). The framework will serialize your .NET object to a JSON encoded result (e.g., { isSuccess: true, id: '1234'}).
As an example, in ASP.NET MVC you simply return a JsonResult using Json.(MySerializableResult). If you post what you are using for web services, I'm sure you'll get a specific answer to that framework.

jquery to convert strings to json to send to my webservice?

Trying to figure out how to convert how to covert 5 variables I have in JavaScript (strings) to a JSON for sending along to my ajax function
here is my ajax function, sill relatively new to this but I believe this should work .. but I need to convert all my strings to a JSON - don't I?
I believe there are alternative ways of sending data without json, but this is the recommended way isn't it?
$.ajax({
type: "POST",
url: "MyService.aspx/SendEmail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function() {
alert('error');
}
});
I believe that at the service end I need to extract the JSON - I am using asp.net
Any ideas?
You do not need to convert to json to pass the data. Just specify the data you need to pass:
$.ajax({
url: "myUrl",
data: {
var1: "some data or var",
dataItem2: false // or a variable
},
success: function(msg) {
alert(msg.d);
},
error: function() {
alert('error');
}
});
The data will be available as request parameters, like so (in Asp.Net):
Request.Params["var1"]
Now if you truely need to receive json on the server, thats a different issue. If thats a requirement, I would be interested in understanding whay.
I suggest you to include in your project JSON2.js, that you can find at this link, and to use the JSON.stringify() function:
...
data: JSON.stringify({ yourVar: "value", var2: "value2" }),
...
if your web service return json data you can parse the result with the library:
success: function(json) { json = JSON.parse(json);
var o = json.d;
...
}
It can assure you that your input data will be sanitized from every illegal character.

Resources