converting object variable to json string for asp.net page method - asp.net

This is probably a very simple task to perform but I'm taking the risk to ask anyway.
I have an object variable that looks like this:
var MyObj = {"Param1": "Default",
"Param2": "test",
"Param3": 3 };
I'm using ASP.net and I'm looking to pass this object to a page method via jquery.
So far, I have this javascript code:
function LoadObject () {
var TheObject = MyObj.toString();
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: TheObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
I have a page method set up in the .cs file and I put a breakpoint in it but it never gets there; nothing happens.
Please let me know what changes I need to make to get this to work.
Thanks.

You need to serialize TheObject into a JSON string, and ensure that the GetCount method accepts an object with the same signature as TheObject.
I use the jQuery.JSON library to do this so that my syntax becomes:
data: "{ methodParameterName: " + $.toJSON(TheObject) + " }"
I use this library, but you can acheive the same thing with any other library in a similar manner

The first thing that you need to know is that you need to match your method name with your url
for example if your method on your code behind is named "calculate", your url must be something like this "../Pages/TestPage.aspx/calculate"
other thing that you need to keep in mind is the parameters of your method, the names and the types of your parameters must match in you ajax call and your method (code behind)
if the sign of your method is something like this
[WebMethod]
public void Calculate(string data){
// your code here
}
Your ajax call must be like this:
function LoadObject () {
var objetoJson = {
data: JSON.stringify(MyObj)
};
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/Calculate",
data: objetoJson ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
This section is so important:
var objetoJson = {
data: JSON.stringify(MyObj)
};
the name "data" is the name of your parameter in your method (code behind) and "JSON.stringify" is a helper functions already defined on your browser to convert and object to string
Hope this helps

Take a look at this thread: JSON stringify missing from jQuery 1.4.1?
Abstract: jQuery doesn't have a native method to do it. But there are many plugins out there.
EDIT
Sample C# code receiving your JSON object:
[WebMethod]
public static int GetCount(GetCountParams p)
{
// ... Do something with p.Param1, p.Param2, etc.
return 0;
}
public class GetCountParams
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
EDIT 2
Sample jQuery AJAX call using that object as parameter:
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: "{ p: '" JSON.stringify(MyObj) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

Related

call a static method in User Control from js or ajax

I am trying to call a static method in User Control from js or ajax.
It is possible to do this if the code method lies directly in WebForm but it is not possible to do it if we put the code method in UserControl and then put this UserControl in a WebForm.
Code Behind:
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static string GetNameFromCodeBehind (string name)
{
return "Hello from Code-Behind, " + name ;
}
AJAX Code:
$.ajax({
type: "POST",
url: "MyUserControl.ascx/GetNameFromCodeBehind",
data: JSON.stringify({ name: "Anton" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: function (data) {
alert(data.d);
},
error: function (e) {
alert(e.statusText)
}
});
Ajax Error:
Not Found
If GetNameFromCodeBehind is inside MyUserControl.ascx, then it will be able to find a URL. Moreover, you have written the name of static method as callFromCodeBehind. So, you need to write the URL sccordingly

json object returns nothing in WCF data service WebInvoke VB Odata

Hope someone can help. Really pulling my hair out and starting to think i should have not used wcf data services. Its been easy to get odata from the service so i thought i could send json object from my javascript code and read the contents as an object in my service But it returns nothing.
My javascript:
var vname = [];
var obj = { myobject: { frmid: "test", frmval: "1111" } }
vname.push(obj)
$.ajax({
url: "MyWCFDataService.svc/SendItems",
type: "POST",
dataType: "json",
contentType: "json",
data: { myobject: JSON.stringify(vname) },
success: function () {
alert("success :-)");
},
error: function () {
alert("fail :-(");
}
});
My class and function in my svc
<DataServiceKeyAttribute("id")> _
Public Class tobject
Public Property id As Integer
Public Property frmid As String
Public Property frmval As String
End Class
<WebInvoke()> _
Public Function SendItems(myobject As String) As Boolean
' have to ask for string as errors when asking for tobject
Return True ' nothing here yet as cannot get json object
End Function
My first venture into wcf data services and jquery. Was hoping to return a list of textboxes names and values to a wcf data service to process. Is it possible with the wcf data service?
Ok so i created a new wcf data service, removed the inherits dataservice reference and initializeservice sub.
javascript:
vname.push( { frmid: "test", frmval: "1111" })
$.ajax({
url: "MyWCFDataService.svc/SendItems",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { JSON.stringify(vname) },
success: function () {
alert("success :-)");
},
error: function () {
alert("fail :-(");
}
});
service:
Public Class tobject
Public Property frmid As String
Public Property frmval As String
End Class
<OperationContract>
<WebInvoke(ResponseFormat:=WebMessageFormat.Json, RequestFormat:=WebMessageFormat.Json)> _
Public Function SendItems(anyobjectname As List(Of tacosobjectitem)) As Boolean
Return True
End Function
This now turns the anyobjectname into a list of my object. I cant understand why i couldnt use BodyStyle:- Wrapped but it works so im happy. Hope it helps someone out there.

how to use jQuery ajax with asp.net user controls?

I want to use ajax with asp.net user control,
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: "{id:'" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
});
.cs code
[WebMethod]
public static string InsertTCSection(string id)
{
string result = "deneme";
return result;
}
You cannot call a method kept inside a usercontrol through jquery.
because .ascx controls don't represent real url.
They are meant to be embedded in some ASP.NET page, hence they don't exist at runtime.
what you might do is, to create a separate service and place your method there.
like webservices.
see this, this and many others
i am using generic Handler to solve this problem.
Try:
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: JSON2.stringify({ id: id}, //Your 2nd id is passing value but i dont know where its come from
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
}
)};
and in cs:
[WebMethod]
public static string InsertTCSection(string id)
{
string result="deneme";
return result;
}
I think you might be missing this attribute
[System.Web.Script.Services.ScriptService]
Before you service class as
[System.Web.Script.Services.ScriptService]
public class TCSection: System.Web.Services.WebService
{
[WebMethod]
public static string InsertTCSection(string id)
{
}
}
Or there may be one other reason that path of the webservice is not right.

Whats the best way to send array of objects from javascript to webservice?

I have in my javascript these 2 functions "classes":
// product class
function Product() {
this.id;
this.qty;
this.size;
this.option;
}
// room class
function Room() {
this.id;
this.type;
this.products = [];
}
I have my js logic which fills rooms and their products.
Now i want to send array of rooms to a webservice to do some calculations and get back from it the result.
How to send this array objects to the service and whats the data type which the service will receive to loop through and process?
I tried to write the javascript code like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "_Services/MyWebService.asmx/CalculatePrices",
data: "{'rooms':'" + roomsObjects + "'}",
dataType: "json",
success: function(result) {
alert(result.d);
}
});
And the webservice like this:
[WebMethod]
public string CalculatePrices(object rooms)
{
return "blabla";
}
but i find that rooms in the wbservice is always = [object Object]
For that case this would work:
//...
data : '{"rooms":[' + roomsObjects.join() + ']}',
//...
The above code will generate a valid JSON string, but I recommend you to get a JSON library and use JSON.stringify function:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "_Services/MyWebService.asmx/CalculatePrices",
data: JSON.stringify({'rooms': roomsObjects}),
dataType: "json",
success: function(result) {
alert(result.d);
}
});
If you don't mind including a tiny JavaScript library, I think using json2.js' JSON.Stringify is the best way to serialize objects for use with ASP.NET AJAX services.
Here's a snippet from that post:
// Initialize the object, before adding data to it.
// { } is declarative shorthand for new Object().
var NewPerson = { };
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'NewPerson' : NewPerson };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PersonService.asmx/AddPerson",
data: JSON.stringify(DTO),
dataType: "json"
});
There's no array in that example, but JSON.Stringify does serialize JavaScript arrays in the correct format to send in to ASP.NET AJAX services for array and List parameters.
A nice thing about using JSON.Stringify is that in browser that support native JSON serializing (FF 3.5, IE 8, nightly builds of Safari and Chrome), it will automatically take advantage of the browser-native routines instead of using JavaScript. So, it gets an automatic speed boost in those browsers.
Change:
data: "{'rooms':'" + roomsObjects + "'}",
to:
data: {'rooms':roomsObjects},

How to post data using jQuery in ASP.NET?

I have an ASP.NET application in which i want to post data using jQuery to another page. It means i want post the data of page.
How can i do this with jQuery or AJAX?
Please help me.
$(document).ready(function() {
alert("start");
$("#btnSave").click(function() {
alert("start1");
var aa = 'bb';
var json = "{'ItemName':'" + aa + "'}";
alert("start2");
var ajaxPage = "Default3.aspx?Save=1"; //this page is where data is to be retrieved and processed
alert("start3");
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
alert("success: " + response);
},
error: function(msg) { alert("failed: " + msg); }
};
alert("start4");
});
});
I am using this code I am getting all alert response but its posting page.
Jquery and JSON works great with ASP.NET. You can call a code behind method directly from javascript and return complex objects, not just string. (for this example to work you need json2.js found here https://github.com/douglascrockford/JSON-js)
//javascript
function postMethod(text){
var jsonText = JSON.stringify({ name:text });
$.ajax({
type: "POST",
url: "yourpage.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function(response) {
var person = response.d;
alert(person.Name);
}
});
}
//aspx code behind
[WebMethod]
public static Person GetPerson(string name)
{
Person person = new Person(name);
return person;
}
There is load function.
You may use it like this:
$('#somediv').load('http://someaddress',{key:value}, function callback(){});
Second parameter is important - only written in this way performs post.(if you pass array then it performs get)
PS> This is good when you want to read the data, if you want to just do the POST and don't care about what comes back then you may want to use:
http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
Look at $.post() - http://docs.jquery.com/Ajax/jQuery.post
Add all your relevant data, and post away, handling the response with the supplied callback method.
There is a post function in jQuery:
$.post("test.php", { name: "John", time: "2pm" } );
This is copied directly from the jQuery API, so for more details and examples you can look there.
jQuery api
choose Ajax > Ajax Requests > $.post

Resources