I have a server-side method used to return the data to the user. The data is stored in a SQL Server database and is mapped using EF 6. Once extracted from the database using an id value, the object is subsequently serialized using the Json.NET framework. The object is used "as is", without filtering out the references to other tables. Because of that, I've had to use the "PreserveReferencesHandling" option.
On the client-side, AJAX is used to call the method. I'm having trouble extracting the data from the object (client-side) which does get serialized and is delivered to the browser as expected.
Server-side method:
[WebMethod]
public static string ContactData(long id)
{
IService<Contact> contactService = new ContactService();
Contact contactEdit = contactService.GetById(id);
string str = JsonConvert.SerializeObject(contactEdit, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
return str;
}
Client-side function (the important part):
$.ajax({
type: "POST",
url: "Contacts.aspx/ContactData",
data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (contact) {
$("#tbFirstName").val(contact.d[0].Contact.first_name); // I've tried various combinations to no avail
},
});
This is how the JSON object (testing purposes data) looks like in Visual Studio's JSON Visualizer:
And this is what the browser (FF 32, it that matters) receives:
Firebug
I will post more info if needed.
First parse the json before you process it. and loop through it using jquery each function.
$.ajax({
type: "POST",
url: "Contacts.aspx/ContactData",
data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (contact)
{
var contact=jQuery.parseJSON(contact);
$.each(contact, function(i, item) {
alert(i + " ==> "+ item.first_name);
});
}
});
Related
I'm using ajax to send an int64 and a string from a month selector to my server-side, but my variable is always null or 0.
JS:
function deleteConta(id) {
var data = $("#monthSelector").val();
var params = {
id: id,
dataAtual: data
};
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
C#:
public PartialViewResult OnPostDelete([FromBody] long id, string dataAtual)
{
contaDTO.Remove(id, contaDTO.Database, contaDTO.ContaCollection);
dataCorrente = DateTime.ParseExact(dataAtual, "yyyy-MM", null).AddMonths(1);
contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
return Partial("_PartialContas", contas);
}
I already checked with debugger and my variables are ok and filled with value expected (One test was like {id: 50, dataAtual: '2023-01'}
Checked a lot of forums, but Couldn't figure out how to make this thing work.
By declaring the number parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class.
Have you tried to remove it and sending value to the action?
—- UPDATE ——
Try this
function deleteConta(id) {
var data = $("#monthSelector").val();
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
data: { id: id, dataAtual: data },
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
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();
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 }),
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.
How can i send a JSON object to a webmethod using jQuery?
Please refer to this article by Dave Ward. It is a complete tutorial on doing this stuff. Also you will find there other great jquery/ASP.net stuff.
EDIT:- Dave is calling method without any arguments, you can replace empty data property with actual data you want to send:
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'name':'tiger1','hobbies':['reading','music']}",//PUT DATA HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
WebMethods expect a string containing JSON that will be parsed on the server-side, I use the JSON.stringify function to convert a parameters object to string, and send the data, I have a function like this:
jQuery.executePageMethod = function(location, methodName, methodArguments,
onSuccess, onFail) {
this.ajax({
type: "POST",
url: location + "/" + methodName,
data: JSON.stringify(methodArguments), // convert the arguments to string
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) {
var jsonData = JSON.parse(data.d);
onSuccess(jsonData, status);
},
fail: onFail
});
};
I recommend you to include the json2.js parser in your pages, to have the JSON.stringify function cross-browser available.
Another library you can use is the jquery-json library. Once included:
var json = $.toJSON(your_object);
The most convenient solutions I've seen simplify this by using the open-source JSON2.js library to parse and 'stringify' complex object data.
These two excellent articles go into detail:
Using complex types to make calling services less… complex by Dave Ward.
JavaScript Arrays via JQuery Ajax to an Asp.Net WebMethod by Chris Brandsma.
The second article might be especially relevant for you, though it calls a web service method with the following signature ...
public void SendValues(List<string> list)
... it demonstrates how to use the JSON2.js library to render a List<string> in javascript (using jQuery, this example is taken directly from the second article):
var list = ["a", "b", "c", "d"];
var jsonText = JSON.stringify({ list: list });
// The 'list' is posted like this
$.ajax({
type: "POST",
url: "WebService1.asmx/SendValues",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { alert("it worked"); },
failure: function() { alert("Uh oh"); }
});
Just use your webmethod URL in lieu of the web service's.
You'd need to post it using Ajax and accept the incoming string on the webmethod. Then you'd need to use the JavaScript deserializer to convert it into an object on the server side.
JSON.stringify does help, but:
it's not cross-browser
take a look here:
http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/#
For browser in-built functions - every browser will have its problems. If You use the above serialization You will need to:
remove newlines with regexp in strings
take care about " in strings
Sample code is here:
var dataString = JSON.stringify({
contractName: contractName,
contractNumber: contractNumber
});
$.ajax({
type: "POST",
url: "CreateQuote.aspx/GetCallHistory",
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.CallHistoryDescription);
OpenLightBox('divDelete');
}
});
[System.Web.Services.WebMethod]
public static object GetCallHistory(string contractName, string contractNumber)
{
return new
{
CallHistoryDescription = "Nalan"
};
}