.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

looping json

Posted By:      Posted Date: October 25, 2010    Points: 0   Category :ASP.Net


how can i loop the following json string in my jquery ajax to populate a dropdownlist. I've tried examples from the web but I get 'undefined'  error.

{"d":"{\"\" : [{\"jobtypeid\" : \"10\",\"jobtype\" : \"Check Clinic Wards\"},{\"jobtypeid\" : \"11\",\"jobtype\" : \"Clear Gas Chambers\"}]}"}
function AjaxSucceeded(response) {
        var models = response.d;               
        for (var i = 0; i < models.length; i++) {
        var val = models[i];
        var text = models[i];
            $('.ccJobTypes').addOption(val, text, false);                    

View Complete Post

More Related Resource Links

WCF Data Service to JSON example? v4


I would like to take WCF Data Service and produce JSON output to consume on various mobile apps.

Can anyone give me a how-to on the JSON part?  I.e., what is different than normal XML outut?



Json Deserialization is giving error in IronPython



Have anyone tried json deserialization. When I tried:

>>> import json

>>> json.loads('["foo", {"bar":["baz", '"Test", 1.0, 2]}]')

I got following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\IronPython 2.6 for .NET 4.0\Lib\json\__init__.py", line
 307, in loads
  File "C:\Program Files\IronPython 2.6 for .NET 4.0\Lib\json\scanner.py", line
42, in iterscan

simple json post url api



I am a json newbie :)

I have this site that has an api that can provide city name if I send my zip code as a parameter. 


the result is returned as a json object. Now i just want to read the result in my js function.

I have tried the following but it always returns null:

function postnr() {
    var url = 'http://www.postnummersok.se/api?q=16447';

Writing Data to database with jQuery Forms, ASMX Webservice, & JSON - help!



Can someone point me in the right direction on how to submit data from a jQuery form to a ASMX webservice? I have gotten everything on the form ready to be submitted to the database and now I am stuck on how to send it over using $.ajax(). Everything I have read tells me how to get data from a webservice and display it with jQuery, but not the other direction nor how to access the json data within the within the webservice service(similar to a Request.Form approach with ASP.NET forms).

In other words: 

1. What do I need to do to my webservice to make sure it can receive data from the jQuery form. 

2. What do I need to do in jQuery to receive an acknowledgement the save on the server side was successful. 

I can explain more if need be, but if there is a comprehensive tutorial on not only reading, but also WRITING data with jQuery, JSON, etc. I would love to get pointed in that direction. 

Looping through DataSet in C#


I have the following line of C# code that successfully returns the results of a stored procudure via a DAL:

spParamGetGamesTableAdapter spGG10 = new spParamGetGamesTableAdapter();

I can bind spGG10 to a DataGrid and see the stored procedure query results, so I know everything is good so far.

I want to loop through the spGG10 (DataSet table?) and output each row on a row-by-row basis using a Literal Control. I think I know how do the output part, so...

My question is: How do I access the data in spGG10 and loop through its records? (Also, I am not exactly sure what kind of object spGG10 really is. Is it a table?)

Thanks in advance.

JSON Deserialize into Entity Framework Object and setting the DataMemberAttribute "Name="




I'm in the process of deserializing a JSON object into an Entity Framework object.  The property names in the JSON do not match up totally with the property names in the Entity Framework Objects. What I'd like to do is set "Name=" on the  "DataContractAttribute" for the table and the "DataMemberAttribute" for the properties in the Designer.cs file.  I tried setting these in the Designer.cs file manually just to see if it would work - which it did (using JSON.Net) but of course when I went into the .edmx designer I lost all my changes.  Is there a way to do this?


Thanks in advance

Looping through controls to find reorderlist to set allowreorder


How would I loop through controls on a content page to set allowreorder of all reorderlists to false. Thank you. 

unable to use wcf service with json in asp.net



I have developed a wcf service for asp.net ajax client. It includes the following steps.

(1) Created WCF sevice contract with the operation "DoWork()" which will take string as input and retun string as output.

(2)Implemented the above operation contract(attributed the implementation class with aspnetcompatibility requirement as enabled).

(3)Added the webscriptenabled to endpoint in web.config file.

(4)Hosted the wcf servie. 

(5)Downloaded the javascript file from the service.(e.g.,http://localhost/service1.svc/js)


(1)Opend new asp.net webapplication.

(2)Added the downloaded .js file.

(3)Given the scripts path for ajaxscript manager as both .js file and service url.


<asp:ScriptManager ID="id1"

Customizing the Converter for Json.NET


Many recently days, I thought about Json.net library that implemented by James. It is really a good library that I have ever used. I really impressed about many Converters that this library expose for user. I can list some converter of json.net at here:

+ BinaryConverter
+ BsonObjectIdConverter
+ DataSetConverter
+ DataTableConverter
+ EntityKeyMemberConverter
+ HtmlColorConverter
+ IsoDateTimeConverter
+ JavaScriptDateTimeConverter
+ KeyValuePairConverter
+ RegexConverter
+ StringEnumConverter
+ XmlNodeConverter

As you see, json.net have many converters, but still not enough for our necessary. So in this post, I try to explorer about 2 converters that I thought it is very useful for us. That are ArrayConverter and Object Converter (it is named by me). In 2 converter, I mainly implement it for return the object's interface, so it can be re-use and extension better. Now this is my code for implement it:
+ CustomObjectCreationConverter

    internal class 

make json call to send an email


the aspx:

<div class="contactSubmit">
                <asp:ImageButton ID="ibSubmit" runat="server" ValidationGroup="vgContact" /></div>


the jquery :

$(document).ready(function () {
            // Add the page method call as an onclick handler for the div.
            $(".contactSubmit").click(function () {
                    type: "POST",
                    url: "Home.aspx/GetDate",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        // Replace the div's content with the page method's return.

The problem is that I need to use the text in a text box in my webmethod, and I can't because it's static, this results in a compilation error:

    public static string SendContactForm()


LinQ Syntax of looping a collection


Hi, I would be glad is there is anyone can point/teach me the correct way of iterate a collection in LINQ. I attached part of my coding for reference. I wish to find out the location(s) of an Employee who can also happen to be a Supervisor. My model contains a Many-to-Many relationship between Location and Employee. Thanks in advance


Dim someDataSource = From _e As Employee In _context.Employees
                                  Where _e.Locations = location <---- _e.Locations return a collection 
                                  Select _e.FullName, _e.ID


Deserialize JSON object in C#

Hi, I am new to JSON and one of my service is returning JSON object as a string to my application. I need to Deserialize JSON object in C#. My JSON string is in the current format. string str = "{\"candidates\":[{\"address\":\"1580 MARKET ST, SAN FRANCISCO, CA, 94102\",\"location\":{\"x\":-122.42054,\"y\":37.7745960000001},\"score\":40,\"attributes\":{}},{\"address\":\"1576 MARKET ST, SAN FRANCISCO, CA, 94102\",\"location\":{\"x\":-122.420355,\"y\":37.7747030000001},\"score\":40,\"attributes\":{}}]}"; Can anyone please help me how to get all the address, locations, score and attributes from the above string. Thankyou, Ravi.

two adjacent double quotes in json causes blue screen by JavaScriptSerializer

Hello, I am using System.Web.Script.Serialization.JavaScriptSerializer to deserialize  http requests.  I get the blue screen when the contents I am deserializing has two double quotes, for example:  ""country"". Is there a fix for this?  Currently I replace the "" with a special string and then I deserialization, then I put back the "".  I do this for a given field in the object which I've seen comes in with ""s.  The problem is that I should be doing this for all fields in the input json.  This is a lot of extra code to write as I could be deserializing many different types of Json objects.  The "" is needed by the client to specify a quoted string, so I can't ask for the input to be changed. Any help on this subject would be really appreciated. Many thanks.     I am using .Net framework 3.5.

SerializationException using JSON Serializer

I'm getting a SerializationException with the following message when I deserialize a simple object serialized with JSON: Expecting element 'root' from namespace ''.. Encountered 'None'  with name '', namespace ''. Any ideas what's wrong?  Here is the code: namespace     JSONSerialization {     class Program { [   DataContract ]     public class Info { [   DataMember ]     public string version; }     static void Main( string [] args) {     Info apiInfo = new Info () {version = "1.0" };     MemoryStream stream1 = new MemoryStream ();     DataContractJsonSerializer ser = new DataContractJsonSerializer ( typeof ( Info )); ser.WriteObject(stream1, apiInfo   );     Info proxyReceived = ( Info )ser.ReadObject(stream1);     Console .WriteLine( string .Format( "{0}: {1}" , "API version" , proxyReceived.version)); } } }

jQuery UI Autocomplete, Web Services and JSON

Hi guys, this is my first post, I´m desperate after wasting 2 days in google and reading forums ans sites. I can´t make it work. I just want to provide the name of cities to show in the autocomplete plugin. Let´s go part by part:WEB SERVICE: I use the Json.Net component to serialize a datasetpublic string ConsultTable(string data) { SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlServerConnection"].ToString()); SqlCommand command = new SqlCommand("SELECT name FROM cities",connection); connection.Open(); DataSet dataset = ToDataSet(command.ExecuteReader()); Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer(); json.NullValueHandling = NullValueHandling.Ignore; json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace; json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; json.Converters.Add(new DataSetConverter()); StringWriter sw = new StringWriter(); Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.None; writer.QuoteChar = '"'; json.Se

How to make my WCF client send JSON?

Hi, I have a WCF Service that accepts and sends JSON objects, defined like the following: [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/booking/", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] Int32 booking(order o); now I have used SvcUtil.exe to create a client class and using that, I am trying to access my service - but even though I use "webHttpBinding" with "webHttp" behavior, it always sends it's messages in xml. What do I have to do make my client speak JSON?  

Routing pox, json & soap

I have a service exposed as pox, json & soap, as described at http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html. It exposes the endpoints: - http://localhost:81/TestService/soap - http://localhost:81/TestService/pox - http://localhost:81/TestService/json I now want to have a router, and to verify functionality, just expose it at http://localhost:82/... and have it forward calls to http://localhost:81/... I get this to work fine with the pox endpoint by following the initial steps at http://msdn.microsoft.com/en-us/magazine/cc500646.aspx, but I can't get it to work with soap or json. How should this be set up to have one router handle calls to all three enpoints? Hälsningar Anders
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend