WCF / ASMX :: Return JSON Data From A 2.0 Web Service?
Sep 10, 2010
Just ramping up on JSON and JQuery and returning data to a ASP.NET web page from a web service using Ajax. The JQuery part is pretty straight-forward. However, when trying to return JSON formatted data instead of XML from a 2.0 web service, I'm stuck. The web service does have the System.Web.Script.Services.ScriptService attribute, so I can hit it via JavaScript; however, the web service always...always...returns data in XML format, no matter if I explicitly say I want JSON as the datatype in my JQuery code. So I don't know if this is an issue with the web service or the JQuery code. I posted this here, but realize that the category could be incorrect depending on where the issue is. Is there no way to return JSON data from a 2.0 web service? It's a production web service, so I can't change the code unfortunately.
I want to return an array of javascript objects from my asp.net asmx file. ie.
variable = [ { *value1*: 'value1',[code]....
I seem have been having trouble reaching this. I'd put this into code but I've been hacking away at it so much it'd probably do more harm than good in having this answered. Basically I am using a web service to find names as people type the name. I'd use a regular text file or something but its a huge database that's always changing - and don't worry I've indexed the names so searching can be a little snappier - but I would really prefer to stick with this method and just figure out how to get usable JSON back to javascript. I've seen a few that sort of attempt to describe how one would approach this but I honestly think microsofts articles are damn near unreadable.
EDIT: I'm using the $.ajax() function from jQuery - I've had it working but it seems like I was doing it in bad practice not returning and using actual JSON. Previously I'd take a string back and insert it into html to use the variable it set - very roundabout.
I'd like to read data server-side from a web service that outputs in json format. I haven't found any good examples that don't use jquery and are server-side.
Specifically I'm looking at the "weight" field from this api:
I Need by service contract to return the xml/json result depending on the request type. function which will convert my result set (i am using linq to sql) so that i do not need to create the xml format for the result set by iterating through the table row many times.What is the suitable way to do that.
I need a kind of short cut method which will convert the table data to xml result.Had i been using asp.net mvc i would have been able to generate the xml data by overriding the the ExecuteResult method in the ActionResult and giving Conetnt-Type = "text/xml" as OP.But since i am using Wcf i don't have the controller context(as controller context is the parameter that needs to be passed to Execute Result).
My present code for converting the table data to the xml format is below.
public XDocument UsersLists(string authToken) { bool IsAuthenticated = Authenticate(authToken); XDocument xDoc = new XDocument(); XElement root = new XElement("Users");
[Code]....
I need to eliminate this way of generating xml for each table records.
After much head scratching as to why my returned Json string is breaking JSON.parse, I have realized that it is the returned dates that it doesn't like.
I just hit the following issue: I am calling a web service that returns a serialized JSON object let's say: __type, FirstName, LastName (.net object Person with properties FirstName and LastName). __type's value is Test.Person
I have created a JS object using Type.registerNameSpace/registerClass called Demo.Person and it is registered on the page using the ScriptManager. Everything is working fine; I am able to get data from the server on the call back.
Is it possible to make the returned object from the web service be an instance of the declared JavaScript Demo.Person class? The idea would be to call a method like result.getFullName() on the client side without having to copy all the properties. This is just a simple scenario for more complex objects.
I have a web service that originally returned a string containing text formatted as XML. I was contacted by the programmer who is going to be consuming the web service, and he asked if I could make it "just XML" and not a string. I converted the web service so that it returns an XMLDocument object, and it seems to be returning data properly. I would just like to erify, however, that the XMLDocument object is what the other programmer was referring to when he said "just XML," and that the XMLDocument can be universally consumed by any programmer, regardless of his or her programming environment.
I am new to web service... I have created a simple web service to add a record to sql server by passing a parameter and returns true or false once done. It the same time, I want to return the customer_account_number value created on the sql server.. so basically I want to return the true and false and one (or more) additional values.
how to create a Web service that returns a JSON(or JSONP). That also should be able to work for cross-domain access aswell as for a local call.. help to get this working or for a few links for further reading about this
Function inside the service simply returns string separated by some delimitor. This string is then used by JS function to assign to a jQuery datatable. Is there a maximum limit on size of this string? I have about 2000 rows with 6 columns each. I get an error (failed handle) when I return them all. But if I do only top 500, it works fine.Is there any size limitation?
I have a webservice - called MyCompany.WebService1
I reference this using a web reference in my ASP.net web application.
Theres a method called "GetDeal" in this web service, that returns a "Deal" Object.
The deal object currently looks (for example) like this:
[code]....
This class is in a different assembly: MyCompany.Model
The web service references this assembly.
In my web app, I can call the GetDeal method. This returns Service1.Deal (service1 is just the name of the web reference)
I can access both properties above. I have now changed the Deal class, and added a couple more properties.
However, I can't see these new properties in my web application. I've updated the web service in the web application. I rebuilt the web service several times, tried removing the MyCompany.Model reference and re-addding it etc...
I can't figure out what has changed... This was working - I have changed the model before, and it's updated the reference correctly...
public AuthenticationResult Authenticate(Enum type, string userName, string password) But the problem I had is that if a null/invalid enum is entered for the type variable it throws an error message.
So the obvious solution is to use a string/int instead but I am cannot do this as current users already use the existing webmethod.
So i was thinking:
public AuthenticationResult Authenticate(object type, string userName, string password) and handling the casting myself but the problem I had with this is that now my users do not have access to the Enum type.
So my question is can I publish the enum type without having it as a parameter/return value? Allow the client to access the Enum so they can pass it into the method. Would using a method that returned a type that was my enum work? Or is there a way to catch this custom error: (I dont think so as it appears to be on the client end when converting Enum to xml). The error is: (System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: Instance validation error: '45465' is not a valid value for Enum.)
I am using JQuery & JSON (POST) to call webmethod. However I can call only webmethod located at aspx file but not in asmx file Below are sample codes
CustomValidate.asmx Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.ComponentModel Public Class CustomValidate Inherits System.Web.Services.WebService 'ACCESS VIA JSON <System.Web.Services.WebMethod()> _ Public Shared Function AJAX_Test(ByVal date1) As Boolean... Return True End Function End Class Javascript: JQuery JSON function isDates(source, arguments) { var isValidDate; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "CustomValidate.asmx/AJAX_Test", data: '{date1: "' + arguments.Value + '"}', dataType: "json", async: false, success: function(result) { isValidDate = result; }, error: function(httpRequest, textStatus, errorThrown) { alert("status=" + textStatus + ",error=" + errorThrown); } }); arguments.IsValid = isValidDate; }
It always return javascript undefined error. But if I put the AJAX_Test webmethod in aspx page and replace the url: "CustomValidate.asmx/AJAX_Test" to "mypage.aspx/AJAX_Test". It works fine.
I am new to WCF, I was using web service asmx before. I have trouble on making my wcf JSON ajax service work through http like asmx.Could you help me see what wrong in my code?My WCF services are defined in my website application folder. My aim is to call this service in my aspx page java-script code and return complex object back as JSON to my javascript. I have no problem on doing this through classic asmx web service.
When I try to test it through my browser by type this in the URL , URL-http://localhost:3849/WebServices/Account/WCFCompanyService.svc/GetAll. it return "Method not allowed."
But if I type just this URL-http://localhost:3849/WebServices/Account/WCFCompanyService.svc, it return this:
WCFCompanyService Service
You have created a service.To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:
This will generate a configuration file and a code file that contains the client class. Add the two files to your client application and use the generated client class to call the Service. For example:
C#
class Test { static void Main() { HelloClient client = new HelloClient();
public dynamic GetReferenceTableData(string tableName) { try { dynamic tableData = ReferenceTableDAL.GetReferenceTableData(tableName); return tableData; } catch (Exception ex) { throw; } } method at DAL(ReferenceTableDAL): public static dynamic GetReferenceTableData(string tableName) { Database db = DatabaseFactory.CreateDatabase(Flags.ConnectionStringKey); DbCommand dbCommand = db.GetStoredProcCommand("USP_GETTABLEDATA"); dynamic objDynamic = null; if (tableName.ToLower() == "a") { objDynamic = new List<A>(); } else if (tableName.ToLower() == "b") { objDynamic = new List<B>(); } else if (tableName.ToLower() == "c") { objDynamic = new List<C>(); } try { db.DiscoverParameters(dbCommand); dbCommand.Parameters["IN_TABLENAME"].Value = tableName; DataSet dsTableData = db.ExecuteDataSet(dbCommand); if (tableName.ToLower() == "a") { foreach (DataRow dataRow in dsTableData.Tables[0].Rows) { objDynamic.Add((A)dataRow); } } else if (tableName.ToLower() == "b") { foreach (DataRow dataRow in dsTableData.Tables[0].Rows) { objDynamic.Add((B)dataRow); } } else if (tableName.ToLower() == "c") { foreach (DataRow dataRow in dsTableData.Tables[0].Rows) { objDynamic.Add((C)dataRow); } } } catch (Exception ex) { throw; } return objDynamic; } @ Aspx try { using (DataServiceRef.DataServiceClient petService = new DataServiceRef.DataServiceClient()) { dynamic tableData = petService.GetReferenceTableData(tableName); //tableData is null ,exception } } catch (Exception ex) { throw; }
There is no exception at dal or service end when i debug list gets filled ok but when returns to aspx error at aspx(no exception gets caught at @ service) but exception at aspx i.e:
Message:The underlying connection was closed: The connection was closed unexpectedly. Stack Trace: at System.Net.HttpWebRequest.GetResponse() at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
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.
we have console-hosted WCF Service and ASP.NET WEB Service (on IIS). After some tough operation WCF Service must return some data(large data) to ASP.NET Web Service for next processing. I tested on small results - everything is ok. But after testing on real data(serialized result object is near 4.5 mb) error occurs on ASP.NET Web Service (which is client in wcf-client-server communication).
Messages size are configured by next binding (on server and client): NetTcpBinding netTcpBinding = new NetTcpBinding(); netTcpBinding.TransactionFlow = true; netTcpBinding.SendTimeout = new TimeSpan(0, 4,0, 0); netTcpBinding.Security.Mode = SecurityMode.None; [code]...