I have some code in JavaScript like this:
slider.setPhotos([
{ "src": "image1", "name": "n1" },
{ "src": "image2", "name": "n2" },
{ "src": "image3", "name": "n3" }
]);
And I want to set the values of src and name from C#.
Assume values are like this in C#:
var images = new string[] {"/images/a1.jpg", "/images/a2.jpg", "/images/a3.jpg"};
var names = new string[] {"First", "Second", "Third"};
How can I set these values into JavaScript code (i.e. in Page Load method in C# code)?
On the server you need to serialize the data as JSON and then you can write it into the response as HTML using something like a hidden input field.
For example you might use the NewtonSoft JSON library to serialize the JSON (which is built into ASP MVC 4 however is easy to install using Nuget)
string json = Newtonsoft.Json.JsonConvert.SerializeObject(images);
Then render the json into the HTML (there are number of methods to do this)
e.g.
Response.Write(string.Concat("<input id='data' type='hidden' value='", json, "' />");
or
HiddenField jsonField = new HiddenField
{
ID = "data"
};
jsonField.Value = json;
this.Controls.Add(jsonField);
or even write directly as script skipping the need to parse on the client (I still tend to use the HTML method to avoid any issues with Postbacks/Update Panels causing the script to be executed multiple times)
Response.Write(string.Concat("<script type='text/javascript'> var images = ", json, ";</script>");
On the client you can then read this JSON from the HTML and parse it. In modern browsers this is built in, or you can polyfill with something like JSON2
e.g.
var field = document.getElenentById('data');
var images = JSON.parse(field.value);
You then have access to the data as a Javascript object.
Assuming that images and names are of same length
You can use this
StringBuilder str = new StringBuilder();
var images = new string[] {"/images/a1.jpg", "/images/a2.jpg", "/images/a3.jpg"};
var names = new string[] {"First", "Second", "Third"};
str.AppendLine("slider.setPhotos([");
for(int i=0; i< images.Length; i++)
{
str.AppendLine("{ \"src\": "+ images[i] +", \"name\": "+ names[i] +" }");
str.AppendLine( (i==images.Length-1 ? "]);":","));
}
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(), "Key007", str.ToString(), true);
This code will insert a script block when your page will be loaded and after that you can use that script block anywhere in your client side code.
Related
I need to do a basic update to a JSON package using FormUrlEncodedContent
At the moment, I can only assign values at parent level.
For example, here's the JSON package that will be sent through the API.
[
{
"id": 29519,
"first_name": "xxxx",
"last_name": "xxx",
"billing": {
"address_1": "xxxx",
"address_2": "xxxx"
}
}
]
At the moment, I can only update the first_name and last_name values using the following code:
var UpdateCustomerAPI = "https://example.com/api/";
var UpdateCustomer_JSON = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("first_name", CustomerFirstName.Text),
new KeyValuePair<string,string>("last_name", CustomerLastName.Text)
});
var httpClient = new HttpClient();
var response = httpClient.PutAsync(UpdateCustomerAPI, UpdateCustomer_JSON);
How do I update the values in billing:address_1 and billing:address_2 using the FormUrlEncodedContent?
You don't: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.formurlencodedcontent?view=netcore-3.1
A container for name/value tuples encoded using application/x-www-form-urlencoded MIME type.
From https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value.
You are not putting a json file to your server. If you want to use it, then you should do something like:
var UpdateCustomer_JSON = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("billing_address_1", CustomerBillingAddress.Text),
});
If you want to post a json file, then you should use application/json mine type and use something like this:
var data = JsonConvert.SerializeObject(customerData);
So I am given a json tree like the one below and I really just need to get the persons first and last names from here but I am having problems parsing the data.
{
"results":[
{
"id":{
"key":"Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable.json?api_key=",
"type":"Phone",
"uuid":"81dd6fef-a2e2-4b08-cfe3-bc7128b43786",
"durability":"Durable"
},
"line_type":"Landline",
"belongs_to":[
{
"id":{
"key":"Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable.json?api_key=",
"type":"Person",
"uuid":"1ffee2ef-cc88-4a1e-87b0-05349571b801",
"durability":"Durable"
},
"type":"Full",
"names":[
{
"salutation":null,
"first_name":"fred",
"middle_name":null,
"last_name":"jones",
"suffix":null,
"valid_for":null
}
],
"age_range":null,
"gender":null,
"locations":[
{
"id":{
"key":"Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable.json?api_key=",
"type":"Location",
"uuid":"bd4721f0-ba97-4ade-aac1-ed1f16be57ed",
"durability":"Durable"
},
"type":"Address",
"valid_for":{
"start":{
"year":2011,
"month":7,
"day":5
},
"stop":null
},
"legal_entities_at":null,
"city":"",
"postal_code":"",
"zip4":null,
"state_code":"",
"country_code":"",
"address":"",
"house":"10",
"street_name":"",
"street_type":"Ave",
"pre_dir":null,
"post_dir":null,
"apt_number":null,
"apt_type":null,
"box_number":null,
"is_receiving_mail":false,
"not_receiving_mail_reason":null,
"usage":null,
"delivery_point":null,
"box_type":null,
"address_type":null,
"lat_long":{
"latitude":,
"longitude",
"accuracy":"Street"
},
"is_deliverable":true,
"standard_address_line1":"",
"standard_address_line2":"",
"standard_address_location":"",
"is_historical":false,
"contact_type":"Home",
"contact_creation_date":1361177323
}
],
The code I have been using so far is:
string url = String.Format("https://proapi.whitepages.com/2.1/phone.json?api_key={0}&phone_number={1}", WhitePagesConstants.ApiKey, number);
using (WebClient webClient = new System.Net.WebClient())
{
WebClient n = new WebClient();
n.Encoding = System.Text.Encoding.UTF8;
var json = n.DownloadString(url);
Dictionary<string, Object> formattedjson = JsonConvert.DeserializeObject<Dictionary<string, Object>>(json);
}
I have been on this for too long and must finish it shortly so I ask please help me traverse this tree. I have never worked with json before and am quite lost on how to do this. The exact info I need is under "belongs_to" -> "names" -> first and last. I've changed some names to protect the innocent.
If all you need is to extract several properties, you can just navigate the path:
dynamic o = JsonConvert.DeserializeObject(json);
Console.WriteLine(o.results[0].belongs_to[0].names[0].first_name);
Console.WriteLine(o.results[0].belongs_to[0].names[0].last_name);
Or, if you prefer string dictionaries over dynamic objects:
JObject j = JsonConvert.DeserializeObject<JObject>(json);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["first_name"]);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["last_name"]);
P.S. Your JSON is broken. It would have been easier for me to test code if you provided a correct example.
I would like to make a Linq query in a json string.
little info about what i'm trying to do. At work we have a web based schedule system which don't have a support for windows 8 and windows phone 8 app. That is why I decided to make one. Using HttpClient I get an http string which I then convert to xml then Json. As you can see from the (Link below, the 'TheWholeJsonString.json' file) the property name and JSON object name is not informative and the JSON file is complicated. That is why I decided to extract some of the values from the JSON string and write a totally new JSON file that include the extracted JSON values in a more informative way.
The [tr] array in the original JSON file have several JSON Objects. Inside the 'VeryShorten.json' file in the linked folder you can see the structure of one of those objects (OBS! there is objcet with different structure). The only thing I hide is the Name and E-Mail address of RL ppl.
I also attached 'ShortenVersion.json' which is only a shorten version of the whole json string, just to make it easy to handle.
Json data sample
{
"#class": "odd",
"td": [
{
"#class": "user",
"#onmouseover": "userInfo('149');",
"#onmouseout": "userInfo(0);",
"#onmousemove": "moveSlotInfo();",
"#text": " ",
"a": {
"#href": "Name3#dreamnet.com",
"#text": "Name3"
}
},
.
.
.
In C# if i try the following code (which is not Linq)
var jObject = JObject.Parse(jString); //jString is 'TheWholeJsonString.json' file in the attached link
var jObj = jObject["tbody"]["tr"][8];
var gh = jObj.Value<JToken>("td").Children().First().Value<JToken>("a").Value<string>("#text");
i can get the value of '#text' which is *'Name3'.
However if i try the following code (Linq version):-
var jObject = JObject.Parse(jString);
var jCollection = jObject["tbody"]["tr"].Children();
var test = from userToken in jCollection
where
userToken.Value<JToken>("td")
.Children()
.First()
.Value<JToken>("a")
.Value<string>("#text")
.Contains("Name3")
select (string)userToken["#text"];
foreach (var item in test)
{
var fgh = item.Type;
}
It will break on the first iteration of foreach loop with the following error msg "Cannot access child value on Newtonsoft.Json.Linq.JValue". I really now what is causing the problem, but i don't know how to solve it. The problem is that not every token inside jCollection have a 'td' object and even if the token have 'td' object it is not Always it have token 'a'. You can see this either in the 'TheWholeJsonString.json' or 'ShortVersion.json' files which i attached in the link.
Hope this will explain more info.
So the question is:- Anyone can help to solve this problem?
You can use SelectTokens method. Notice false as second parameter - don't generate error if element is not found.
var jObject = JObject.Parse(jString);
var trList = jObject["tbody"]["tr"];
string[] names = trList.SelectMany(tr => tr.SelectTokens("td[0].a.#text", false))
.Select(t => t.Value<string>())
.ToArray();
You can easily query with LINQ like this
considering this JSON
{
"items": [
{
"id": "10",
"name": "one"
},
{
"id": "12",
"name": "two"
}
]
}
putting it in a variable called json like this,
JObject json = JObject.Parse("{'items':[{'id':'10','name':'one'},{'id':'12','name':'two'}]}");
you can select all ids from the items where name is "one" using the following LINQ query
var Ids =
from item in json["items"]
where (string)item["name"] == "one"
select item["id"];
I have these data in thhe codebehind and tried to pass it to javascript function in various formats: array of list, json string but no way to get data by a javascript var object.
Here is the last format of data in the code behind:
List<string>[] array2 = new List<string>[listLenght];
array2.Initialize();
for (int ii = 0; ii < listLenght; ii++)
{
array2[ii] = new List<string>();
array2[ii].Add(Convert.ToString(dt.Rows[ii][5]));
array2[ii].Add(Convert.ToString(dt.Rows[ii][9]));
array2[ii].Add(Convert.ToString(dt.Rows[ii][10]));
array2[ii].Add(Convert.ToString(dt.Rows[ii][11]));
}
Then tried to call javascript in this way:
string createArrayScript = string.Format("var array2 = [{0},{1},{2},{3}];",
string.Join(",",",",",", array2));
But returns an error:
FormatException was unhandled by user code.The index (zero based) must be greater than or equal to zero and less than the size of the list of topics
This is the call to the function:
Page.ClientScript.RegisterStartupScript(this.GetType(), "registerPoiArray", createArrayScript, true);
Here is the javascript var format:
var markers = Poi;
var markers = [
{
"title": "via Andria, Roma",
"lat": 41.8902643,
"lng": 12.6638589,
"description": "fdsad"
},
{
"title": "via canosa, Roma",
"lat": 41.8838417,
"lng": 12.5438227,
"description": "fdsad"
},
{
"title": "via taranto, Milano",
"lat": 45.4383343,
"lng": 9.1505354,
"description": "fdsad"
},
{
"title": "via barletta, Roma",
"lat": 41.9102707,
"lng": 12.4580826,
"description": "fdsad"
}];
I can not pass this array in javascript.
You can create a custom class to represent the Datatable. Say if your data table has four columns, create a custom class which has 4 fields in it. Loop through the data table and convert it in to an array of objects of the custom class type.
Finally you can serialize the array into json using the following code.
JavaScriptSerializer js = new JavaScriptSerializer();
js.Serialize(data);
where data is the array of objects.
This is the technique i used..
Data table cannot be serialized easily to JSON directly. refer What's the best way to jSON serialize a .NET DataTable in WCF?
You have to escape (double up) the curly brace when using String.Format if you want it to spit out the actual curly brace character.
Example:
string createArrayScript =
string.Format("var array2 = [{{0}},{{1}},{{2}},{{3}}];",
...
Try to use
System.Web.Helpers.Json.Encode
And change the structure you are getting.
List<object> toEncode=new List<object>();
foreach (DataRow dr in dt.Rows){
Dictionary<string,string> element=new Dictionary<string,string>();
element.Add("title",dr["title"] as string);
//repeat for all neaded colums
toEncode.Add(element);
}
string jsonString=Json.Encode(toEncode);
I created a gist when I put the solution.
I hope this works for you...
Regards,
Just use NewtonSoft Json and call:
var JsonString = JsonConvert.SerializeObject(NameofDT, Formatting.Indented)
I have a JSON like this:
var commpanyTags = "[{\"label\":\"Citizen\",\"category\":\"Companies\"},{\"label\":\"Citi Bank\",\"category\":\"Counterparties\"}]";
Is it possible to convert it to
var commpanyTags = [ { label: "Citizen", category: "Companies" }, { label: "Citi Bank", category: "Counterparties" } ];
If it is possible, how to do that?
JSON.parse (here) will do the job if you are in JavaScript land.
If you are in C#, then consider using JSON.NET to parse the JavaScript into a C# object.
var commpanyTags = jQuery.parseJSON( commpanyTags );