Read and Parse JSON data from POST request in C# - c#

I'm doing a POST request via JQuery's Ajax, with the type of data defined as json, containing the values to be posted to server, something like Username: "Ali".
What I need to do in a Handler, is to read the values, deserialize them to an object named User.
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
User user = JsonConvert.DeserializeObject<User>(data);
While debugging, the value of data is the following:
Username=Ali&Age=2....
Now I'm sure this isn't JSON, so the next line would certainly produce an error:
"Unexpected character encountered while parsing value: U. Path '', line 0, position 0."
What is the proper way to read JSON data from POST request?
Client Side
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: {
Username: 'Ali',
Age: 2,
Email: 'test'
},
success: function (data) {
},
error: function (error) {
}
});

Convert your object to json string:
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: JSON.stringify({
Username: 'Ali',
Age: 2,
Email: 'test'
}),
success: function (data) {
},
error: function (error) {
}
});

I am not sure why your datastring is encoded like an url (as it seems).
But this might solve the problem (altough i am not sure)
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
String fixedData = HttpServerUtility.UrlDecode(data);
User user = JsonConvert.DeserializeObject<User>(fixedData);

Use This In c# file... Will give you result you require...
string username=Request.Form["Username"].ToString();
Similarly For others...
I hope this will help you
Another Answer Or you can send data like this
$.ajax({
url: '../Ajax/Ajax_MasterManagement_Girdle.aspx',
data: "Age=5&id=2"
type: 'POST',
success: function (data) {
}
});
ANd get the answer like this in c#
string Age=Request.Form["Age"].ToString();

Related

How to get data from POST url ajax

Using ajax POST a url http://test/jy/post.php will get some value below
People,1220,temperature,26C,CO2 concentration,30ppm,3.jpg
Want to put each of them separately into my input text.
Trying to alert data, but it show [object],don't know how to do.
Here is my js:
window.onload = load();
function load() {
$.ajax({
url: 'http://test/jy/post.php',
type: 'POST',
success: function (data) {
},
error: function (data) {
alert(data);
console.log(data);
}
});
}
Hope someone can tell me how to do it or hint me , thanks!
I am assuming that the data in the POST response is JSON.
As mentioned by #Kaushik you can use JSON.stringify(data) to convert the JSON data to a string.
First of all, I would recommend that you take a look at the content at the following link which explains JSON objects and how to work with them. JSON Objects - W3 Schools
For my examples, I have used https://jsonplaceholder.typicode.com/todos to return example JSON data.
If you wish to only access certain properties of the JSON object then you could accomplish this using the following code. Please bear in mind that the following code snippet assumes that the JSON object consists of a single record.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: 'json',
success: (data) => {
console.log('User ID: ' + data.userId);
console.log('Title: ' + data.title);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If the JSON data consists of an array of JSON objects then you could approach this with the following code.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos',
dataType: 'json',
success: (data) => {
data.forEach((record) => {
console.log('User ID: ' + record.userId);
console.log('Title: ' + record.title);
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If you simply just want to display all JSON data as a string then the following code would accomplish this.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: 'json',
success: (data) => {
console.log(JSON.stringify(data));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Ajax error when there's a parameter in url

I have a ajax code that fills a dropdownlist and I use mvc c#.
When I call to my method from ajax and I have an url in the directions bar without parameters the code works correctly, but if I have a parameter in url in the directions bar this not working and appears this error:
"{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}".
Here's my code:
$.ajax({
url:"../Records/myList",
type: "POST",
dataType: 'json',
contentType: 'application/json',
// data: JSON.stringify(Data),
success: function (resul) {
Function(resul);
},
error: function (message) {
}
});
My url: http://localhost:123/Record/EditRecord ->> so it's works
My other url: http://localhost:123/Record/EditRecord/1 ->> It does not work like this
Thanks in advance.
From given second URL (which doesn't work) I assume that you want to use jQuery AJAX with HttpGet method. The URL pattern matches this route:
http://localhost:123/{controller}/{action}/{id}
which id treated as UrlParameter.
Hence you need to use action argument & data representing URL parameter values, like this example:
Controller
[HttpGet]
public ActionResult EditRecord(int id)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "GET",
dataType: 'json', // response type
contentType: 'application/x-www-form-urlencoded; charset=utf-8', // header content type
data: { id: 1 },
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Alternatively a direct usage of URL parameter is applicable for GET methods without specifying data content:
View (JS)
$.ajax({
url: "Record/EditRecord/1",
type: "GET",
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
NB: Use jQuery.get for simplified version:
$.get("/Record/EditRecord/1", function (result) {
Function(result);
}, "json").error(function (message) { // throw error
});
PS: This is an example for HTTP POST request if you're looking for proper POST method with AJAX.
Controller
[HttpPost]
public ActionResult EditRecord(Record rec)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "POST",
dataType: 'json', // response type
contentType: 'application/json; charset=utf-8', // header content type
data: JSON.stringify({ rec: { id: 1, name: 'XXXX', ... }}),
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Reference:
Do GET, POST, PUT, DELETE in ASP.NET MVC with jQuery AJAX
i cant see any fault in the code but i suggest to try let the param come with it's name at server either if you choose to use data propery (of ajax function):
{key1: 'value1', key2: 'value2'}
or you use string query:
page?name=ferret&color=purple
bacuse you've just say that first method was work i assume there is no need to check POST/GET method.
EDIT:
be award to this.

asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'

I want to insert data from JavaScript to database using ajax and webservice,
I have some controls which by jQuery I get their values and make an array of their values.
When I send the array it causes this error:
Cannot convert object of type 'System.String' to type'System.Collections.Generic.List1[System.String]'
var variables = Array();
var i=0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
variables[i] = $(this).find('.selected').find(".text").html();
i++;
});
$.ajax({
type: 'post',
data: "{ 'a':'" +variables + "'}",
dataType: 'json',
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
}
});
This is the C# Code
[WebMethod]
public object insertAd(List<string> a)
{
return a;
}
You need to make your data parameter of the $.ajax call like this: JSON.stringify({'a': variables})
The JSON variable is not available in < IE8 so you'll want to include a JSON implementation like the one mentioned in the answer here
Also, you had an extra } in the success function.
So, in the future, if you want to add extra parameters to your data object passed to the web service, you'd construct it like so:
var someArr = ['el1', 'el2'];
JSON.stringify({
'param1': 1,
'param2': 'two'
'param3': someArr
// etc
});
JavaScript:
var variables = Array();
var i = 0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
variables[i] = $(this).find('.selected').find(".text").html();
i++;
});
$.ajax({
type: 'post',
data: JSON.stringify({'a': variables}),
dataType: 'json',
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
});
});
C#
[WebMethod]
public object insertAd(List<string> a)
{
return a;
}
data: Data to be sent to the server. It is converted to a query string, if not already a string. It’s appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So, try to add a new parameter to your ajax call:
$.ajax({
type: 'post',
data: { 'a': variables }, // Notice some changes here
dataType: 'json',
traditional: true, // Your new parameter
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
}
});
Try this way. Maybe you'll need to change the Web service method to expect an array instead of a List, but I'm not sure.
Try this
data: JSON.stringify({ 'a': variables }),

Send complex data to C# with jQuery

I have a JavaScript object like so that I want to send to C# (question right at the bottom)
var data = {
mykey1: "somevalue",
mykey2: "somevalue2",
addProducts: [
{
id: 1,
quantity: 3,
variation: 54
},
{
id: 2,
quantity: 5,
variation: 23
}
]
}
It is to add either a single product or multiple products to a users basket. I want to send an array of objects back..
I can access this in Javascript by using
data.addProducts[1].id
using the below...
$.ajax({
url: "/ajax/myurl",
data: data,
dataType: "json",
type: "GET",
success: function( response ){
// Data returned as JSON
}
});
it is sending the data like this (URLdecoded for your reading pleasure)
?mykey1=somevalue&mykey2=somevalue2&addProducts[0][id]=1&addProducts[0][quantity]=3&addProducts[0][variation]=54&addProducts[0][id]=2&addProducts[0][quantity]=5&addProducts[0][variation]=23
My question is... without using JSON.stringify on the data, which will just send it as a full object in the url /ajax/myurl/{mykey1:1 ...}
How can I read this information back in from C#? jQuery is just encoding it as the standard way, should I be doing anything else to this, and is there a built in way to grab this data in C#?
var strValue = $(getStringValue);
var intValue = $(getIntValue)
$.ajax({
type: \"post\",
url: \"default.aspx/getData\",
data: \"{\'postedAjaxStringValue\"\': \'\" + encodeURIComponent(strValue) + \"\', postedAjaxIntValue: \" + encodeURIComponent(intValue ) + \"}\",
contentType: \"application/json; charset=utf-8\",
dataType: \"json\",
success: OnSuccess,
failure: function (response) {
error: function (response) {
});
//ON C# KodeBehind..
[System.Web.Services.WebMethod]
public static string getData(string postedAjaxStringValue, int postedAjaxIntValue){}

Javascript - jquery ajax post error driving me mad

Can't seem to figure this one out.
I have a web service defined as (c#,.net)
[WebMethod]
public string SubmitOrder(string sessionid, string lang,int invoiceno,string email,string emailcc)
{
//do stuff.
return stuff;
}
Which works fine, when I test it from the autogenerated test thingy in Vstudio.
But when I call it from jquery as
$j.ajax({
type: "POST",
url: "/wservice/baby.asmx/SubmitOrder",
data: "{'sessionid' : '"+sessionid+"',"+
"'lang': '"+usersettings.Currlang+"',"+
"'invoiceno': '"+invoicenr+"',"+
"'email':'"+$j(orderids.txtOIEMAIL).val()+"',"+
"'emailcc':'"+$j(orderids.txtOICC).val()+"'}",
contenttype: "application/json; charset=utf-8",
datatype: "json",
success: function (msg) {
submitordercallback(msg);
},
error: AjaxFailed
});
I get this fun error:
responseText: System.InvalidOperationException: Missing parameter: sessionid. at
System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection) at
System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request) at
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
data evaluates to: {'sessionid' : 'f61f8da737c046fea5633e7ec1f706dd','lang': 'SE','invoiceno': '11867','email':'steve#jobs.com','emailcc':''}
Ok, fair enough, but this function from jquery communicates fine with another webservice.
Defined:
c#:
[WebMethod]
public string CheckoutClicked(string sessionid,string lang)
{
//*snip*
//jquery:
var divCheckoutClicked = function()
{
$j.ajax({
type: "POST",
url: "/wservice/baby.asmx/CheckoutClicked",
data: "{'sessionid': '"+sessionid+"','lang': '"+usersettings.Currlang+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
divCheckoutClickedCallback(msg);
},
error: AjaxFailed
});
}
data: {sessionid: sessionid,
lang: usersettings.Currlang,
invoiceno: invoicenr,
email: $j(orderids.txtOIEMAIL).val(),
emailcc: $j(orderids.txtOICC).val()
},
Refer to http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/
Short version is,
Be sure to set data as a string using this format
// RIGHT
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
url: 'WebService.asmx/Hello',
data: '{ FirstName: "Dave", LastName: "Ward" }'
});
it has to be double quotes inside the string.
You can simplify the JSON creation and make it less brittle by using JSON.stringify to convert a client-side object to JSON string. JSON.stringify is built into newer browsers as a native feature, and can be added to older browsers by including Douglas Crockford's json2.js.
Take a look at this post on using JSON and data transfer objects with ASMX ScriptServices for some examples. Its examples start in almost exactly the same predicament that you're currently in, so hopefully it will be helpful.
remove the single quotes;
data: "{sessionid : "+sessionid+","+
"lang: "+usersettings.Currlang+","+
"invoiceno: "+invoicenr+","+
"email:"+$j(orderids.txtOIEMAIL).val()+","+
"emailcc:"+$j(orderids.txtOICC).val()+"}",
contenttype: "application/json; charset=utf-8",
and move the curly brace outside the quotes
data should be more like data: {sessionid : sessionid, lang: usersettin...
the way you're sending it now, it's a string.. so your application is NOT getting the variable sessionID and it's value.
Thus, it's reporting an error. this error is not json, so responseText is throwing an error.

Categories

Resources