Send JSON to webmethod? - c#

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"
};
}

Related

Ajax Webmethod not being called

I make a total of four Ajax calls in my .NET application. Three of them work without a hitch except the last one.
Note: I HAVE to use .aspx for these calls and not mypage.aspx/mymethod because of our architectural constraints.
Ajax call that works:
$.ajax({
type: "POST",
url: "myaddress/GenerateOpinionHTML.aspx",
data: JSON.stringify({ id: featureId, pageNumber: pageNumberIndex }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
SOME PROCESSING (IT WORKS)
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log(err);
}
});
and
[WebMethod]
public static string GenerateOpinionHTML(int id, int pageNumber)
{
// ...
}
Ajax call that does not work:
console.log("SUBMITOPINIONCLICK");
var param = " ";
$.ajax({
type: "POST",
url: "myaddress/SaveOpinion.aspx",
data: JSON.stringify({ parameter: param}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SAVE OPINION SUCCESSFUL");
console.log(msg.d);
CloseLB('GiveOpinionLB');
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log("ERROR " + "STATUS: " + status);
}
});
and
[WebMethod]
public static string SaveOpinion(string parameter)
{
// ...
}
The web method SaveOpinion is never called according to the logs. Do you have any ideas or suggestions? I tried adding parameters, without parameters, checking my web.config file (though I shouldn't have since the other calls work)...
The error I get on the browser console is a "parseerror". I'm certain I wouldn't be getting an error if the method was called.
I think your URL should be like
url: "Your FolderName/PageName/Function Name",
Like
url: "myaddress/SaveOpinion.aspx/SaveOpinion"
but in your code this is different so that please check.
Have you checked if method SaveOption return something to the client?
If you specify dataType as json, you should return (at least): {}
Ok so we "solved" it. We just found a very dirty band-aid workaround that works.
We made a custom handler (.ashx) that we defined in our architecture as a SaveOpinion.aspx page.
We then called this custom handler page with jQuery and voilĂ  it works, we had to obviously pass all necessary parameters manually, ie. fetching all values from textBoxes etc with jQuery and not from the context as we did before.
Since this is run in some sort of thread (I don't really know the details) we had to configure it so that it simulates the same user authentification.
Anyway I hope this provides some measure of guidance for those with this kind of obscure problems.

JavaScript - extracting data from a JSON object created with Json.Net

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);
});
}
});

FileUpload formData in ASP.NET WebForms

I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this
It is impossible to call a server method
[WebMethod]
public HttpPostedFileBase Name(HttpPostedFileBase file)
{
string ret = "test";
return file;
}
Errors on the client side no
I wrote jQuery function that need to post form data to server using ajax call.
this is my script:
data.append(self.idFileInput, file[f]);
$.ajax({
type: "POST",
url: "/AddContract.aspx/Name",
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
}
});
Any tips, link or code example would be useful.
Thank you in advance!
try to use contentType: 'application/json; charset=utf-8',
$.ajax({
type: "POST",
url: "AddContract.aspx/Name",
data: { field1: self.idFileInput, field2 : file[f]} ,
dataType: 'json',//Remove this line this line is causing issue.
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (data) {
}
});
In a previous answer I said something stupid about ASPX not supporting WebMethod calls, which they do.
Now a real answer:
In order to post a file you need to use the ajaxSubmit method. See this reference.

Ajax JQuery Passing Data to POST method

I am a newbie at javascript and jquery and I would like some help if possible. I searched and tried to make it work, but I think I am missing something simple.
I have the following method in my cs file (CeduleGlobale.aspx.cs)
[WebMethod]
public static void SetSession(string data)
{
HttpContext.Current.Session["salesorderno"] = data;
}
I also have a some javascript in my ascx file
<script type="text/javascript">
function SetSession() {
var request;
var values = 'fred';
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
request.done(function () {
alert("Finally it worked!");
});
request.fail(function () {
alert("Sadly it didn't worked!");
});
}
</script>
The function in the script is called by
<dx:ASPxCheckBox ID="cbxHold" runat="server" AutoPostBack="true" Text="OnHold" ClientSideEvents-CheckedChanged="SetSession">
</dx:ASPxCheckBox>
And the result i keep getting is "Sadly, it didn't work!".
I know the problem is not with anything relative to the path of the url, because it worked when i passed NULL as data and had the method with no parameters.
The parameters and data is what i tripping me I believe.
You should pass serialized JSON into the method:
var values = JSON.stringify({data:'fred'});
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
You are specifying that you are sending JSON, but you don't serialize the value to JSON, so try changing the request to this:
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: JSON.stringify({data: values}), // 'stringify' the values to JSON
contentType: "application/json; charset=utf-8",
dataType: "json"
});
'fred' is not json nor object
use object notation :
{"myattr":"fred"} //you can also do {myattr:"fred"}
and then use JSON.stringify which transform it into STRING representation of json object.
The data sent through post should be sent in a {key:value} format
values={name:'fred'}
The data should be passed into [key:value] pair.

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