On the server side I create a list
List<object> data = new List<object>();
for (var j = 0; j < items.Count(); j++)
{
var temp = groups.Where(customfilter);
data.Add(Html.Raw(Json.Encode(temp)));
}
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
var serializedData = serializer.Serialize(data);
Inside Javascript the folowing won't work for anything but primitive types.
var localData = #data;
This is the error:
System.Collections.Generic.List`1[System.Object]
What am I missing?
I am assuming that the C# code you posted is a Controller action method.
You would need to have your controller method return a JsonResult, and then use a JSON library to deserialize it.
Something like
public class MyController: Controller
{
public JsonResult MyAction ()
{
var data = new List<object>();
for (var j = 0; j < items.Count(); j++)
{
var temp = groups.Where(customfilter);
data.Add(temp);
}
return Json (data, JsonRequestBehavior.AllowGet);
}
}
Note how you don't need to serialize every item as you add it to the list.
From the client side, you can call your method and deserialize the result to a list. You can do it like this:
$.ajax ({ url:'/My/MyAction'}).done (function (data) {
var myList = JSON.parse (data);
});
Edit:
After some testing, I found that you can access the data by doing:
var myList = data;
Not sure why, but "data" is sent directly as an array.
Hope it helps!
First of all check this link http://james.newtonking.com/pages/json-net.aspx
Second
var temp = groups.Where(customfilter).ToList();
If you use where cast it to list or it will be something like Query object *(I dont remember exactly type)
Or if you want to select one object try groups.FirstOrDefault
Third
data.Add(temp);
Serializer will do his job to convert it.
Related
I simply worked with Transaction in ArnagoDB_NET when I work with one item of my model. but I have a problem when I want to pass a list of my model.
var transactionResult= Context.Transaction.WriteCollection("User").Execute<Dictionary<string, object>>(
string.Format(#"
function () {{
var db = require('internal');
if(!db.User.exists('{0}'))
db.User.save( {{ _key:'{0}', UserAppState:1 }});
}}
// and other actions
return {{ 'Executed': true }};
}}", myModel.userId))
above example fine worked, but when I want to pass a list of my model, how can I iterate them into string(or ArangoDB script)?
for example:
string.Format(#"
function () {{
var db = require('internal');
for (i = 0; i < {0}.count; i++){{ // I know didn't work this block code!
if(!db.User.exists('{i.key}'))
db.User.save( {{ _key: ""'i.key'"", UserAppState:1 }});
// and other actions
}}
return {{ 'Executed': true }};
}}", lstMyModels);
can any one help me?!
I don't think this would be possible given your example, since you are combining C# string interpolated object with ArangoDB transaction functionality which doesn't work together just by combining them into single query.
Your first example works because it's using primitive value which you pass into the string, however in the second example you want to pass list of objects and iterate through them using cycle that is not in any way connected to the list itself. This line
for (i = 0; i < {0}.count; i++) {
won't work because lstMyModels is a C# list object and you would actually end up with a string interpolated like this:
for (i = 0; i < System.Collections.Generic.List`1[System.Object].count; i++) {
which makes no sense to the ArangoDB which needs to execute the transaction. Moreover the i variable is a simple number serving as current cycle iteration index therefore calling i.key is also wrong.
Instead of complicated string interpolation you should try to use transaction parameter passing which is supported by the ArangoDB-NET driver.
EDIT:
Let's say you have object like this:
public class TransactionEntity
{
public string Foo { get; set; }
}
Then you can pass it as transaction parameter for example like this:
var transactionData = new List<TransactionEntity>
{
new TransactionEntity
{
Foo = "string1"
},
new TransactionEntity
{
Foo = "string2"
},
new TransactionEntity
{
Foo = "string3"
}
};
var transactionResult = db.Transaction
.WriteCollection("myCollection")
.Param("data", transactionData)
.Execute<List<TransactionEntity>>(#"
function (params) {
var db = require('internal').db;
for (var i = 0; i < params.data.length; i++) {
db.myCollection.save(params.data[i]);
}
return db._query('FOR doc IN myCollection SORT TO_NUMBER(doc._key) RETURN doc').toArray();
}
");
I'm trying to loop over a JSON string in my Android app. This is the code I have so far, using answers I found on line.
private void updateAutoComplete() {
var testJSON = "{result:[{\"symbol\":\"FB\",\"typeDisp\":\"Equity\",\"exchDisp\":\"NASDAQ\",\"exch\":\"NAS\",\"name\":\"Facebook, Inc.\",\"type\":\"S\"},{\"symbol\":\"FB2A.DE\",\"typeDisp\":\"Equity\",\"exchDisp\":\"XETRA\",\"exch\":\"GER\",\"name\":\"Facebook, Inc.\",\"type\":\"S\"}]}";
var autoCompleteOptions = getAutoCompleteOptions (testJSON);
ArrayAdapter autoCompleteAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleDropDownItem1Line, autoCompleteOptions);
var autocompleteTextView = FindViewById<AutoCompleteTextView>(Resource.Id.AutoCompleteInput);
autocompleteTextView.Adapter = autoCompleteAdapter;
}
private String[] getAutoCompleteOptions(String json) {
var autoCompleteOptions = new String[20];
int i = 0;
dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach (var data in dynObj.result) { //x
autoCompleteOptions.SetValue (data.symbol, i);
i++;
}
return autoCompleteOptions;
}
Want I want is to get the different symbols from the JSON in an array so I can use it for the autocomplete.
When I run the app (updateAutoComplete is called in the OnCreate), I get following error: 'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'result' on the line marked with the x.
Anyone know what might be the problem?
Thanks in advance.
If you are trying to go the route of not serializing back into an object you can cherry pick the data out of the string that you need with a JObject.
JObject root = JObject.Parse(testJSON);
var result = (JArray)root["result"];
result.ToList().ForEach(x =>
{
var symbol = x["symbol"];
symbol.Dump();
});
//FB
//FB2A.DE
I have retrieved data from the database and put it in a List. I need to access this list of items using Jquery and put them in a dropdown list. Here is my code in the Controller
//filling list with data from data reader
List<Object> list=new List<Object>();
while (read.Read())
{
var var1 = (int)read["dbColumn"];
var var2 = (string)read["dbColumn2"];
list.Add(var1);
list.Add(var2);
}
var serializer=new System.Web.Script.Serialization.JavaScriptSerializer();
string theData = serializer.Serialize(list);
return theData;
In my jquery I have this
if (!$.isEmptyObject(data))
{
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i].dbColumn];
var second = [data[i].dbColumn2];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html("<option>"+html+"</option>").show();
}
Then I have this as the Html code where I want the list to be displayed
<select id="SelectBox"></select>
When I try this, I get a looooooong list of empty option fields. What could be the issue
Don't wrap content of select control in <option>.
$('#SelectBox').html(html).show();
You are just returning a serialized List<Object> so there isn't a dbColumn1 or dbColumn2 in your result.
It might be worth creating a wrapper class or using a Dictionary<int, string> for your results but to make it work using your current code you can change your jQuery code to:
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i]];
var second = [data[++i]];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html(html).show();
Note that for the second value we are just incrementing i to get to the next item in the list. We are also just using the value from data[i] directly rather than trying to access any properties from it as it is just an array of items.
This gives a select box populated something like this:
Edit
It would seem from the comments that the Json being returned is not being parsed correctly as well as having your indexing and naming incorrect as per the above. Assuming you are using the jquery.ajax() method to retrieve the Json it is probably treating the returned item as a string. From the documentation on the dataType parameter (emphasis mine):
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
You could change your call to pass dataType: 'json' and as per the documentation jQuery will automatically parse it into a JavaScript object:
ajaxReq = $.ajax({
url: '/home/something',
dataType: 'json', //get jQuery to parse the response for us
success: function (data) {
//data is now a parsed JS object
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i]];
var second = [data[++i]];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html(html).show();
}
});
If you want to parse the json manually or you are using a different method to retrieve the results you could parse the json yourself by adding
data = JSON.parse(data);
before the line var len = data.length;
var batch= document.getElementById('id');
$(batch).append($("<option></option>").val(first ).html(second ));
Note :Id get using browser.ie(insepect element).
I am having a trouble doing this: I have a ViewBag that contains the list of documents Id's and the response time for each one, created like this:
Controller:
ViewBag.Documents= (from n in db.DocumentType
select new {a = n.DocumentTypeId, b=n.ResponseTime});
Based on the document that the user selected on a dropdownlist, the javascript code calculates the real duration of processing the document (duration).
DocumentId(int) Response(int)
1 2 days
2 3 days
3 1 day
The complete javascript code calculates the final date based on response time without weekends and holidays, but the only part that it is not working is the following part of JavaScript code:
JavaScript at the view:
function CalculateTime(documenttype) {
var duration= 0;
var jScriptArray= new Array();
var array = '#Html.Raw(Json.Encode(ViewBag.Documents))';
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < 2; j++) {
jScriptArray [i][j] = array [i][j];
}
}
for (i = 0; i < jScriptArray.length; i++) {
if (documenttype== jScriptArray [i][0]) duration= jScriptArray [i][1];
}
return duration;
}
I already have the correct documenttype variable based on a dropdownlist but this script is not working. I think is the way I want to use the ViewBag, but I am not pretty sure. What I need to know is: what is wrong with my code or another way to do this.
Thanks in advance
Just remove quotes
var array = #Html.Raw(Json.Encode(ViewBag.Documents));
Just remove the quotes(') and you have to Newtonsoft.Json for this.
var array = #Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Documents);
This will work.
A friend of mine helped me solve my problem. Some of you told me to use Json, so we did this:
Controller:
using System.Web.Script.Serialization;
using Newtonsoft.Json;
...
var timeList= db.DocumentType.ToList();
ViewBag.ResponseTimes= new JavaScriptSerializer().Serialize(
JsonConvert.SerializeObject(new
{
times= (from obj in timeList
select new { DocumentTypeId= obj.DocumentTypeId, ResponseTime= obj.ResponseTime})
}, Formatting.None));
JavaScritp at the View:
function CalculateTime(documenttype) {
var duration = 0;
var jScriptArray = new Array();
var array = $.parseJSON(#Html.Raw(ViewBag.ResponseTimes));
for (i = 0; i < array.times.length; i++) {
if (parseInt(documenttype) == array.times[i].DocumentTypeId) {
duration= array.times[i].ResponseTimes;
}
}
return duration;
}
Thanks!
PS: I don't know which of both answers give the acceptance cause we used part of both....
I want to call one javascript function from my button click on server side and pass the arraylist, string array or list as a parameter to the function.
I would then need to iterate through all the elements of these collection and perform some action on the data.
Can you tell me the javascript code to access these element
Consider the following structure that I have in the Javascript
Function ABC(_Arraylist/List/String Array){
//I would like to perform some action on the collections data here.
}
Thanks.
Server:
// this could also be a string[] if you prefer
var array = new List<string> { "foo", "bar", "baz" };
var serializer = new JavaScriptSerializer();
var script = string.Format("foo({0});", serializer.Serialize(array));
ClientScript.RegisterStartupScript(GetType(), "call", script, true);
Client:
function foo(array) {
for (var i = 0; i < array.length; i++) {
alert(array[i]);
}
}