WebMethod Return Values In JSON Format?
Jan 24, 2010
How to return values from Webmethod to the client in JSON format? There are two static int values that i want to return.Do I need to create new object with those 2 properties and return it?The GetStatus() method is called frequently and i don't like the idea of creating a special object each time just for json formatting...
[WebMethod]
public static int GetStatus()
{
int statusProcess,statusProcessTotal;
Status.Lock.EnterReadLock();
statusProcess=Status.Process; //Static field
statusProcessTotal=Status.ProcessTotal; //Static field
Status.Lock.ExitReadLock();
return ...
}
On client side I catch the return value in :
function OnSucceeded(result, userContext, methodName)
(PageMethods.GetStatus(OnSucceeded, OnFailed);)
View 1 Replies
Similar Messages:
Jun 7, 2010
I have the following web method , no success on return a correct Json format.
[Code]....
GetAll() return list of type "Company" POCO classes.
The web method complaint type "Company" could not cast to object. However I could not just return the Company type because client side Json only accept its 2 properties -"CompanyName", "ID" and I want to keep it that way.
Of cause, I had tried create a CompanyDTO which only have those two properties, but same error - "Unable to cast object of type..."
How should I modify in my web method to make it able to return a list of partial "Company" type in Json format?
View 4 Replies
May 7, 2015
I am trying to retrieve asp.net C# List method in JavaScript by referring Send-and-receive-JavaScript-Array-to-Web-Service-Web-Method-using-ASP.Net-AJAX ..My Code as below
Javascript
<script type = "text/javascript">
function GetAllSVGData() {
PageMethods.GetSvgElements(OnSuccessSVGElements);
}
function OnSuccessSVGElements(response) {
[code]....
My problem is JavaScript function OnSuccessSVGElements is not firing. When I put breakpoints in it is working fine in C#. C# Method Working But Alerts in javascript not working.
View 1 Replies
Sep 28, 2010
Upon clicking a button I need to send a collection and a few other variables to server in Json form.For each value in the collection the server code (C# ) wil update those other variables in the DB.
For example there is a ‘classnumber’ collection with values (First, Second, Third, ….),other variables (‘teacher_name’ and ‘subjectname’).For each value in the ‘classnumber’ collection I need to update the ‘teacher_name’ by searching for the ‘subject_name’ in the DB.So I need to pass the ‘classnumber’ collection,’teacher_name’,’subject_name’ values to server in json form. At the moment instead of sending the ‘classnumber’ collection I am sending ‘teacher_name’,’subject_name’,’classnumber’ as variables for each value in the collection ,which requires multiple requests made to the server.
Instead of these individual requests I am wondering if there is a way to send all the data at once to server in json form?
View 1 Replies
Jun 11, 2010
I was using Extjs to send a json object to my asp.net webservice/Update method , but I find the following error in firebug reseponse.
[Code]....
View 1 Replies
Oct 30, 2010
how would i go about returning a generic list in json format, can anyone point me to any good examples.
View 2 Replies
May 7, 2015
i want to return multiple(name and statusid) parameter from web method and want to retrive in javascript function how to use it.Â
I have attached my code.Â
[System.Web.Services.WebMethod]
public static string CheckPromotionCode(Int32 id)
{
string name="kausha";
string statusId = "6";
[CODE]...
View 1 Replies
Feb 19, 2010
I'm completely new to both VB.NET and JSON, and I'm trying to figure out how to do SQL queries towards an SQL 2005 Express server and format the return value to JSON. I got the queries working using this (perhaps very newbie-like) code;
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls
Partial Public Class SQLConnect
Inherits System.Web.UI.Page
'Defines SQL variables
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim ReadData As String
Dim i As Integer
Sub Click(ByVal s As Object, ByVal e As EventArgs)
'Define SQL address, database, username and password
con.ConnectionString = "Data Source=localhostSQLEXPRESS;Initial Catalog=tempdb;User ID=tesst;Password=test"
Try
'Initialize connection
con.Open()
'Specify SQL query
cmd = New SqlCommand("SELECT * FROM Member", con)
'Execute query, dump result array into variable
dr = cmd.ExecuteReader()
messageLabel.Text = "<br />Connection established<br />"
While (dr.Read)
i = 0
For i = 0 To dr.FieldCount - 1
'Dump query results into a variable
ReadData += dr.Item(i).ToString
Next
End While
'Print query results
messageLabel2.Text = ReadData
'Close connection
con.Close()
Catch ex As Exception
messageLabel.Text = "<br />Connection failed<br />"
End Try
End Sub
End Class
I have been looking at this, and I would love to see some code examples using this class or any other good method.
View 3 Replies
Jan 22, 2010
Can my WebMethod return an XmlDocument as return type?
When I try to consume the web service I'm still not getting XML. It appears as though a reference to the method is being returned rather than say a string containing XML.
<WebMethod()> _
Public Function CustomerSearch(ByVal lastName As String, ByVal firstName As String, ByVal companyName As String, ByVal city As String, ByVal state As String, ByVal email As String) As XmlDocument
' Create XML doc
Dim doc As XmlDocument = New XmlDocument()
' some more code
Return doc
End Function
View 4 Replies
Feb 1, 2010
I want to retreive the data from database and assign it to dropdownlist. For that I'm using the following jquery in the onclick event
[Code]....
View 1 Replies
Jun 8, 2010
I have an asp.net page with a WebMethod on it to pass JSON back to my javascript. Bellow is the web method:
[WebMethod]
public static string getData(Dictionary<string, string> d) {
string response = "{ "firstname": "John", "lastname": "Smith" }";
return response;
}
When this is returned to the client it is formatted as follows:
{ "d": "{ "firstname": "John", "lastname": "Smith" }" }
The problem is the double quotes wrapping everything under 'd'. Is there something I've missed in the web method or some other means of returning the data without the quotes? I don't really want to be stripping it out on the client everytime. Also I've seen other articles where this doesn't happen.
View 2 Replies
Feb 15, 2010
I have the following JSON class I am intending to use to perform management calls on my database asynchronously:
<script type="text/javascript">
var CalendarManager = {
defaultOptions: {
staffcode: 0, // required
date: 0, // required
[Code]....
Basically, my question is: how do I specify optional parameters to a WebMethod when providing JSON data?
I know I can reduce the parameters down to just the required values, and then use HttpContext.Request.Params to read the values of optional paramaters, but I would have thought the way I have tried here should have worked.
EDIT
The XMLHttpRequest.responseText value for the error is:
Invalid JSON primitive: staffcode.
This is throwing me even more off the scent of the problem :(
View 2 Replies
Mar 13, 2012
I'm doing an jQuery AJAX POST call to a webmethod, which is working fine. If I'm passing data from the AJAX call, I normally get the data in the webmethod via webmethod parameters.
JavaScript Code:
$.ajax({"dataType": "json","contentType": "application/json","type": "POST","url": "Default.aspx/GetStuff","data": JSON.stringify({"a":"data1","b":2}),"success": function (msg) {Â Â console.log(msg.d);}});
C# Code:
[WebMethod]public static object GetStuff(string a, int b){Â }
Is there any way I can get the data as a Dictionary or some other object, instead of having to put in individual parameters to the GetStuff() web method for each data param? It's a POST request so nothing is in Request.QueryString, and Request.Params/Request.Form doesn't contain it either.
View 2 Replies
Sep 10, 2012
This is regarding your article onÂ
[URL]
I have a json object with multiple Name & Value pairs, Â I am using example on above given link but it is not calling the Web Method.
var jd = [];
jd.push({ ID: HArr[j], Val: Str });
var jd = [];
[Code].....
In my class I have a Web Method defined as :
[System.Web.Services.WebMethod]
public static jsonData PassJsonData(jsonData jd)
{
return jd;
}
View 1 Replies
Nov 30, 2010
I'm using jquery autocomplete to call a .aspx page which returns some matching words.
The jQuery stuff relies on a JSON feed to work. Currently, in my C# I'm formatting the output as a string, which ouputs something like this:
{ query:'aa','aardvark','aardvarks']}
I was hoping that because the string is formatted in the JSON format, that would be good enough for the Javascript to process but it appears not.
how to format this text in C# into proper JSON format which JavaScript can deal with properly?
View 1 Replies
Oct 12, 2010
ASP.NET [WebMethod] does it always return XML?
I know it can only return serializable data types.
View 1 Replies
Nov 27, 2010
My Problem is that i am returning a json string from a webmethod from an aspx page.
I want to create a dynamic html table using that json string but found no solution for that.
Can anyone Provide me the solution to generate html table from json string ?
View 6 Replies
Mar 8, 2011
public class JsonBuilder
{
private StringBuilder json;
public JsonBuilder()
{
json = new StringBuilder();
}
public JsonBuilder AddObjectType(string className)
{
json.Append(""" + className + "": {");
return this;
}
public JsonBuilder Add(string key, string val)
{
json.AppendFormat(""{0}":"{1}",", key, val);
return this;
}
public JsonBuilder Add(string key, int val)
{
json.AppendFormat(""{0}":{1},", key, val);
return this;
}
public string Serialize()
{
return json.ToString().TrimEnd(new char[] { ',' }) + "}";
}
}
Here is the Web Method [WebMethod]
public static string GetPersonInfo(string pFirstName, string pLastName)
{
var json = new JsonBuilder().AddObjectType("Person");
json.Add("FirstName", "Psuedo" + pFirstName).Add("LastName", "Tally-" + pLastName);
json.Add("Address", "5035 Macleay Rd SE").Add("City", "Salem");
json.Add("State", "Oregon").Add("ZipCode", "97317").Add("Age", 99);
return json.Serialize();
}................
View 1 Replies
May 7, 2010
i have used AjaxToolkit:AutoCompleteExtender, which calls a web method to get string array. Everything was working fine as its populating all the data.But the issue arise when web method is returning value in a string array like
arr[0]=1-12-100
arr[1]=1-10-100
the value im getting in the AutoCompleteExtender is the subtract of the result like
arr[0]=-111
arr[1]=-109
Why is it treating it like numeric and doing calculation when the return type is actual an string. i think its has to do sth with serialize and deserialize thing
View 1 Replies
Jan 14, 2011
I have a web Method in my C# that is called via Jquery ajax method. The web method should return an object back to the Jquery which will be used to populate. I have tried returning a JsonResult object, the actual object and nothing seems to work! I'm not using MVC (Unfortunately). Is there a way that I can return an object from my web method which can be used by my AJAX method? here is the link for my JQuery AJAX method [URL]
View 1 Replies
Sep 22, 2010
I have an Ajax function called from JQuery that goes to a webservice to return a value. I need a SIMPLE example on how I can do this. I've been going nuts with serializing and every other aspect of this topic. I need to return either an ArrayList with ONE string field or a DataTable of some kind. Either way, I'm populating it into a DropDownList. I'm willing to consider alternatives to this idea. (Background info - I get a value from a textbox and I need to run it through a DB to get an associated value or set of values). I'm being really general so that someone can show a simple example.
View 15 Replies
Jul 19, 2010
In my asp.net website I need to return data obtained from DB by adding html tags to it from a server side method,just like a webmethod returns jsonified data. I am having trouble understanding if a webmethod can serve the purpose(i.e., htmlifying the data).If not how do I acheive it?
View 1 Replies
Mar 31, 2010
I am calling a WebMethod from this code:
if($(this).attr("checked")) {
..
MyWebMethod(variable1, variable2, onSuccessFunction);
}
The MyWebMethod returns an integer, and I want to set $(this).attr("id") of the jQuery object above to the returned integer. Basically, I'm trying to do the equivalent of an MVC Ajax.ActionLink...AjaxOptions {UpdateTargetID =...} However, I can't figure out how to get both a reference to $(this) as well as the returned value. For example, if I do:
MyWebMethod(variable1, variable2, onSuccessFunction($(this)));
I can succesfully manipulate the jQuery object, but obviously it doesn't have the return value from the MyWebMethod. Alternatively, the first code block with a method signature of onSuccessFunction(returnValue) has the correct return value from MyWebMethod, but no concept of the jQuery object I'm looking for. Am I going about this all wrong?
View 1 Replies
Jul 9, 2010
i would like to display phone number fields on a website as (123) 456-7890 but have the system see it as 1234657890 when calling myTextBox.Text i am thinking this would require overriding the text property and cleaning it up in the overridden property but wanted to run this past the community.
View 2 Replies
Feb 4, 2011
I have a controller that uploads a file. I would like to return a json result with bool success (if successfully uploaded otherwise false) and message (this could be error message that occured OR link to a file OR link to an image, depending on what was uploaded).What's the best way to approach thisI have this
public class UploadedFile
{
public bool Success { get; set; }
public string Message { get; set; }
}
then In my controller I would set Success to true/or/false and Message to <a href OR <img am i on the right track?How would i then parse this in the view so that when image it will show an image, if link show a link, if error simply alert error.
View 2 Replies