C# ListItemCollection to JSON, while keeping values and text items - javascript

I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!

One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]

Related

Deleting a key in JSON while making ajax call from javascript

I am new to java script and ajax. I have a JSON and I want to remove outputs cell in this JSON:
{
"cells": [{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "print(\"hi\")",
"execution_count": 1,
"outputs": [{
"output_type": "stream",
"text": "hi\n",
"name": "stdout"
}]
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "Python [Root]",
"display_name": "Python [Root]",
"language": "python"
},
"anaconda-cloud": {},
"language_info": {
"pygments_lexer": "ipython3",
"version": "3.5.0",
"codemirror_mode": {
"version": 3,
"name": "ipython"
},
"mimetype": "text/x-python",
"file_extension": ".py",
"name": "python",
"nbconvert_exporter": "python"
},
"gist": {
"id": "",
"data": {
"description": "Untitled5.ipynb",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
and this is my attempt on removing the outputs cell. This piece of code posts the data to above mentioned JSON:
"use strict";
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
var outputs = data.cells;
var data_dup = _objectWithoutProperties(data, ["outputs"]);
var id_input = $('#gist_id');
var id = params.gist_it_personal_access_token !== '' ? id_input.val() : '';
var method = id ? 'PATCH' : 'POST';
// Create/edit the Gist
$.ajax({
url: 'https://api.github.com/gists' + (id ? '/' + id : ''),
type: method,
dataType: 'json',
data: JSON.stringify(data_dup),
beforeSend: add_auth_token,
success: gist_success,
error: gist_error,
complete: complete_callback
});
};
But this code doesnt work. Can some one please guide how can we directly strip a key(outputs in this case) from ajax call and post it to JSON.
This is a gist extension of jupyter notebook and I am trying to strip output while posting it to gist on github
function _objectWithoutProperties(obj, key="outputs") { obj.cells.forEach(cell=>delete(cell[key])); }
If you use ES6, you can use this syntax to remove outputs:
{
...data,
cells: data.cells.map(({ outputs, ...otherProps }) => otherProps),
}
Note: data is your complete object.

Unable to bind json data (api result) to dropdown using jquery/js in MVC

I want to bind json data returned by API to dropdownlist.
but unable to fetch value id and name.
Json Format :
{
"categories": [
{
"categories": {
"id": 1,
"name": "CatOne"
}
},
{
"categories": {
"id": 2,
"name": "CatTwo"
}
}
]
}
I am returning JsonResult, using
return Json(responseData, JsonRequestBehavior.AllowGet);
and in Jquery call ,I am using
$.ajax({
type: "POST",
url: "/Home/City",
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
success: function (jsonObj) {
var listItems = "";
//here I want to get id and name
});
}
});
You can populate dropdown from your json like following.
var json = {
"categories": [
{ "categories": { "id": 1, "name": "CatOne" } },
{ "categories": { "id": 2, "name": "CatTwo" } }
]
}
$.each(json.categories, function () {
$('select').append('<option value="' + this.categories.id + '">' + this.categories.name + '</option>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>
You can just stick a break point (or debugger; statement) inside your success callback. Then you can inspect your jsonObj and it'll tell you exactly what you need to know.
In this case, you should be able to iterate on jsonObj.categories, and your id and name properties will be accessible via jsonObject.categories[i].categories.id and jsonObject.categories[i].categories.name
So your success method will look something like:
for(var i = 0; i < jsonObj.categories.length; i++) {
var category = jsonObj.categories[i].categories;
var id = category.id;
var name = category.name;
}
I would also suggest formatting your json differently, as other answers have suggested.

Get Child JSON Values from Objects

I have an endpoint with two JSON Objects as follows:
{
"main" {
"id": 1,
"title": Main Title,
},
{
"secondary" {
"id": 3,
"title": Secondary Title,
},
I am using backbone and have the following $each function, but using dot notation, I can't seem to be able to browse to the titles (ex. main.title or secondary.title). What am I missing?
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(response, function (index, value) {
console.log(value.main.title);
$("#test2").append('<li>' + value.main.title + '</li>');
});
In my console, it gives an error of: Uncaught TypeError: Cannot read property 'title' of undefined
Assuming your JSON is actually valid when returned (it isn't valid the way you show it), try
$("#test2").append('<li>' + value.title + '</li>');
Your actual JSON should look like:
{
"main": {
"id": 1,
"title": Main Title,
},
"secondary": {
"id": 3,
"title": Secondary Title,
}
}
If you just want the value of main, instead of using $.each(), remove that entire block and do:
$("#test2").append('<li>' + response.main.title + '</li>');
And your final code would look something like:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
if (response.main.title !== 'undefined'){
$("#test2").append('<li>' + value.main.title + '</li>');
}else{
console.log('Main is undefined');
}
}
});
Final Edit: It looks like you want JSON like:
{
"main": [{
"id": 1,
"title": "Main Title"
}, {
"id": 2,
"title": "Main Title 2"
}, {
"id": 3,
"title": "Main Title 3"
}],
"secondary": [{
"id": 5,
"title": "Secondary Title 5"
}, {
"id": 34,
"title": "Secondary Title 34"
}, {
"id": 36,
"title": "Secondary Title 36"
}]
}
If that is the case your code would look like:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(function(index, value){
$.each(item_index, item_value){
$("#test2").append('<li>' + item_value.title + '</li>');
}
});
}
});
The problem lies with input JSON, it should be
{
"main" :{
"id": 1,
"title": "Main Title"
},
"secondary":{
"id": 3,
"title": "Secondary Title"
}
}

Convert JSON Object to a simple array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following nested JSON Object coming from this call:
var jsonData = jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: "json",
async: false
}).responseText;
{
"d": {
"results": [
{
"__metadata": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)",
"etag": "W/\"1\"",
"type": "Microsoft.SharePoint.DataService.ProjectHoursItem"
},
"ContentTypeID": "0x0100C5D130A92A732D4C9E8489B50657505B",
"Title": "Ryan Cruz",
"Hours": 35,
"Id": 1,
"ContentType": "Item",
"Modified": "/Date(1373535682000)/",
"Created": "/Date(1373535682000)/",
"CreatedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/CreatedBy"
}
},
"CreatedById": 19,
"ModifiedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/ModifiedBy"
}
},
"ModifiedById": 19,
"Owshiddenversion": 1,
"Version": "1.0",
"Attachments": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/Attachments"
}
},
"Path": "/sites/itg/Resourcecenters/spwidgets/Lists/ProjectHours"
},
{
"__metadata": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)",
"etag": "W/\"1\"",
"type": "Microsoft.SharePoint.DataService.ProjectHoursItem"
},
"ContentTypeID": "0x0100C5D130A92A732D4C9E8489B50657505B",
"Title": "Phillip Phillips",
"Hours": 25,
"Id": 2,
"ContentType": "Item",
"Modified": "/Date(1373535694000)/",
"Created": "/Date(1373535694000)/",
"CreatedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/CreatedBy"
}
},
"CreatedById": 19,
"ModifiedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/ModifiedBy"
}
},
"ModifiedById": 19,
"Owshiddenversion": 1,
"Version": "1.0",
"Attachments": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/Attachments"
}
},
"Path": "/sites/itg/Resourcecenters/spwidgets/Lists/ProjectHours"
}
]
}
}
I want to loop through each object's Title and Hours attribute and save them in an array so I can pass it to the google chart as below:
var data = google.visualization.arrayToDataTable(array);
I tried the following code, but it can't find the json object:
function drawTable() {
var jsonData = jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: "json",
async: false
}).responseText;
alert(jsonData);
var obj = jQuery.parseJSON(jsonData);
//alert(jsonData.length);
var sampleData = [], results = d.results;
for (var i = 0, len = results.length; i < len; i++) {
var result = results[i];
sampleData.push({ Title: result.Title, Hours: result.Hours});
}
var data = google.visualization.arrayToDataTable(obj);
var chart = new google.visualization.PieChart(document.getElementById('spChart'));
chart.draw(data, {showRowNumber: true});
}
Please give me some ideas so i don't get stuck here for the rest of the day. Thank you!
jQuery.getJSON({"http://testsite/_vti_bin/listdata.svc/ProjectHours",{},function(d) {
var sampleData = [], results = d.results;
for (var i = 0, len = results.length; i < len; i++) {
var result = results[i];
sampleData.push({ Title: results[i].Title, Hours: results[i].Hours});
};
});
OK, I am answering my own question here in case someone runs across something similar.
This was an ajax call to a MS SharePoint site returning list data in JSON.
jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: 'JSON',
success:function(data) {
//jQuery('#spChart').append(JSON.stringify(json));
//var obj = jQuery.parseJSON(data);
var rowArray = [], results = data.d.results;
for (var i=0; i < results.length; i++)
{
var result = results[i];
rowArray.push([result.Title, result.Hours]);
//rowArray.push(["'" + result.Title + "'", result.Hours]);
}
},
error:function(){
alert("Error");
}
});
I had to first refer the json being returned as 'data' and access each javascript object inside of it as data.d.results[0], data.d.results[1], data.d.results[2] etc by looping through each of them.

Filter select options based on data-* attribute

I have 2 select menus on my page.
First have 3 values: All, Active, Unactive and second is filled with data that comes from server.
I need to connect them, so that when I select an option from the first select menu, the second select will have only certain options (filter second select menu)
My idea was to get data from server with 3 elements:
[ { "Id": 1, "Name": "Active One", "Active":true },
{ "Id": 2, "Name": "Active Two", "Active":true },
{ "Id": 3, "Name": "Unactive One", "Active":false },
{ "Id": 4, "Name": "Unactive Two", "Active":false } ]
Second thing that I do is adding all options with custom attribute to that select:
<option value=' + n[index].Id + ' data-active='+n[index].Active+'>' + n[index].Name + '</option>
I have problem with filtering second select.
I've wrapped filling second select inside a plugin so it will be easier to reuse it.
Here is jsFiddle demo: http://jsfiddle.net/Misiu/pr8e9/4/
What I would like this to work is after filling select from server user will be able to select every option from second select, but when he will change first select the second one will update-show only appropriate options.
So if he'll select Active he will be able to select only Active One or Active Two.
EDIT: This is working solution thanks to #oe.elvik
Alternative solution:
(function ($) {
var meinData;
$.fn.createOptions = function(filter) {
var $this = this;
var n = meinData
var list = "";
for (var index = 0; index < n.length; index++) {
if(filter == -1 || (filter == 1 && n[index].Active) || (filter == 0 && !n[index].Active)){
list += '<option value=' + n[index].Id + ' data-active='+n[index].Active+'>' + n[index].Name + '</option>';
}
}
$this.filter("select").each(function () {
$(this).empty();
$(this).append(list);
if ($.ui.selectmenu && defaults.selectmenu) {
$this.selectmenu();
}
});
}
$.fn.ajaxSelect = function (options) {
var $this = this;
//options
var settings = $.extend({}, defaults, options);
//disable select
if ($.ui.selectmenu && settings.selectmenu && settings.disableOnLoad) {
$this.selectmenu('disable');
}
//ajax call
$.ajax({
type: settings.type,
contentType: settings.contentType,
url: settings.url,
dataType: settings.dataType,
data: settings.data
}).done(function (data) {
meinData = data.d || data;
$($this).createOptions(-1)
settings.success.call(this);
}).fail(function () {
settings.error.call(this);
});
return this;
};
var defaults = {
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/echo/json/',
dataType: 'json',
data: null,
async: true,
selectmenu: true,
disableOnLoad: true,
success: function () {},
error: function () {}
};
})(jQuery);
$(function () {
var data = {
json: $.toJSON({
d: [{ "Id": 1, "Name": "Active One", "Active":true }, { "Id": 2, "Name": "Active Two", "Active":true },{ "Id": 3, "Name": "Unactive One", "Active":false }, { "Id": 4, "Name": "Unactive Two", "Active":false }]
}),
delay: 2//simulate loading
};
function ok() {
$('select#me').selectmenu({ select: function(event, options) {
$('select#mein').createOptions(options.value)
}
});
}
function error() {
alert('there was a problem :(');
}
$('select#me').selectmenu().selectmenu('disable');
$('select#mein').selectmenu().ajaxSelect({
data: data,
success: ok,
error: error
});
});

Categories

Resources