I have a datatable i wish to use defer render on, I am not sure what the issue is, my controller method returns an array of json objects. See code below.
**Datatable setup **
This is called when the page is loaded.
var $dtTable = $("#tblPlayer");
$dtTable.dataTable({
bFilter: false,
pageLength: 10,
paging: true,
autoWidth: true,
columns:
[
null,
{ "orderDataType": "dom-text", type: "string" },
{ "orderDataType": "dom-text", type: "string" },
{ "orderDataType": "dom-text-numeric" },
{ "orderDataType": "dom-text-numeric" },
{ "orderDataType": "dom-text-numeric" },
{ "orderDataType": "dom-text-numeric" },
{ "orderDataType": "dom-text-numeric" },
null,
null,
null
],
"ajax": "Player/GetSetPlayers",
"deferRender": true
});
Controller methods
public object[] GetSetPlayers()
{
var players = GetPlayers();
_players = new object[players.Count];
for (var i = 0; i < players.Count; i++)
{
_players[i] = players[i];
}
return _players;
}
GetSetPlayers() returns an array of json objects, the result below is an exampel of what index 0 and 1 will contain.
Response
[
{
"product":25000,
"rank":1,
"dirty_money":25000,
"id":"b4b41b18edbb49b9ae80be5e768b6b80",
"name":"Dan",
"ban_status":0,
"edit":"<a href='/support/player_gamedata/b4b41b18edbb49b9ae80be5e768b6b80/game' class='btn'><i class='icon-folder-close'></i></a>",
"credit":30,
"clean_money":20000,
"ban":"<a href='/support/ban_player/by_id/b4b41b18edbb49b9ae80be5e768b6b80/' class='btn'><i class='icon-remove'></i></a>",
"supplies":25000
},
{
"product":25000,
"rank":1,
"dirty_money":25000,
"id":"3cac6e366170458686021eaa77ac4d6d",
"name":"Dan",
"ban_status":0,
"edit":"<a href='/support/player_gamedata/3cac6e366170458686021eaa77ac4d6d/game' class='btn'><i class='icon-folder-close'></i></a>",
"credit":30,
"clean_money":20000,
"ban":"<a href='/support/ban_player/by_id/3cac6e366170458686021eaa77ac4d6d/' class='btn'><i class='icon-remove'></i></a>",
"supplies":25000
}
]
I think you need to specify a "data" attribute on each column that needs to be populated from the returned data. Otherwise it doesn't know what attribute on the json object goes to each column. If you defined your data as an array of arrays instead of an array of objects this wouldn't be required.
Additionally you aren't specifying a "dataSrc" option which isn't required but if it isn't set I believe it expects the returned JSON to be of the form:
{
data: [ {...}, {...} ]
}
So it would be helpful if you could add in the raw response to the ajax request.
EDIT1:
Ok so double checked and yes it does want an object array assigned to the "data" attribute on the JSON object so you can do something like this to fix this without having to modify anything on the server. Just change your ajax option to this:
"ajax": {
"url": "Player/GetSetPlayers",
"dataSrc": function ( json ) {
// We need override the built in dataSrc function with one that will
// just return the object array instead of looking for a "data"
// attribute on the "json" object. Note if you ever want to add
// serverside sorting/filtering/paging you will need to move your table
// data to an attribute within the JSON object.
return json;
}
}
So you will probably be good once you do both of the fixes above.
Related
My Json looks like below.
I want to check if the following key/nodes exist or not in the below Json.
1st node-> AutomationFramework.Technique.Available
2nd node->Verify.Customer
{
"$type": "Config",
"Available": true,
"Verify": {
"$type": "UserList`2"
"Customer":"Peter"
},
"Identification": true,
"Verification": false,
"AutomationFramework": [
{
"$type": "custom",
"Name": "ATL",
"Technique": {
"$type": "Technique",
"PropertyName": "Name",
"Available": true
},
"SolveTechnique": {
"$type": "Userdefined",
"Available": true
},
"AITechnique": {
"$type": "AI",
"X_Value": 2,
"Y_Value": 3,
"Available": true
},
"WaitTechnique": {
"$type": "Recurssion",
"Available": true
}
}
]
}
I tried with the following code (ParseJson below is a method to parse JSON which I have created):
JObject obj = JObject.Parse(ParseJson(#"C:\Test\Test.Config"));
IEnumerable<JToken> token = obj.SelectTokens("AutomationFramework.Technique.Available", errorWhenNoMatch: false);
Here it is returning null even if the node is present.
I want a generic method that could handle all scenarios. Any help will be appreciated.
The method should return True/False based on the existence.
Your code is not working because AutomationFramework is a list, not an object.
Also, be sure to cast the result to an appropriate type. If you know the type of the token, you can cast directly in place. If you don't know the type at compile time, you can store in a JToken variable instead.
In your code you are using SelectTokens. But if you are expecting only one of that token, you should use SelectToken instead.
Assuming that the desired node Technique will always be present in the first item of the AutomationFramework list, you could do:
JObject obj = JObject.Parse(ParseJson(#"C:\Test\Test.Config"));
bool avail = (bool)obj.SelectToken("AutomationFramework[0].Technique.Available", errorWhenNoMatch: false);
string cust = (string)obj.SelectToken("Verify.Customer", errorWhenNoMatch: false);
I have the following json called 'originalJson'
{
"user_active": true,
"user_firstname": "Bob",
"user_lastname": "Tester",
"user_displayname": "Bobby",
"user_primary_email": "bob#tester.com",
"user_login_enabled": true,
"user_profile": {
"user_locale": "en-gb",
"user_lang": "en-gb"
},
"user_identities": [],
"user_roles": [
{
"app_id": "74a019c9-7171-4af0-a773-3984edaa35ca",
"context_uuid": "74a019c9-7171-4af0-a773-3984edaa35ca",
"context_type": "context_application",
"role_oid": "test_role_a",
"role_start_date": "2020-06-27T13:00:00Z",
"role_end_date": "2021-06-27T13:00:00Z"
}
]
}
and I am trying to replace the role_start_date and role_end_date values.
I have tried the following
JObject jObj = JObject.Parse(originalJson);
jObj["user_roles"]["role_start_date"] = somenewstartDate;
jObj["user_roles"]["role_end_date"] = somenewendDate;
However it is failing and doesn't like the "jObj["user_roles"]["role_start_date"]". I thought it would be pretty simple to do, I must be missing something.
Any ideas?
The property "user_roles" is an array of objects not a single object. You are trying to set a property value in the first entry in that array, so you need to do:
jObj["user_roles"][0]["role_start_date"] = somenewstartDate;
jObj["user_roles"][0]["role_end_date"] = somenewendDate;
I have dynamic keys and values that I get from db and then parse with Newtonsoft Json.NET but I don't know how can I serve them as static ones.
Example
This is what I have
{
"Id": 1,
"IsPublic": false,
"Notes": "",
"Values": [
{
"Key": "1",
"Value": "12.02.1991"
}
]
}
This is what I want
{
"Id": 1,
"IsPublic": false,
"Notes": "",
"Values": [
{
"1": "12.02.1991"
}
]
}
What I have tried
I tried to do it manually inside my query itself but it didn't work since it's trying to assign the value.
return _db.Archives.Single(x => x.Id == id).Batches.SelectMany(x => x.Items).Select(item => new
{
item.Id,
item.IsPublic,
item.Notes,
Values = item.ArchiveFieldValues.Select(value => new
{
/*
This works just fine
Key = value.ArchiveField.Key,
Value = value.Value
*/
// This is what I tried but it does not work
value.ArchiveField.Key = value.Value
})
}).AsQueryable();
First off, it's complex enough that you probably want to pull it out into it's own function.
You can use an ExpandoObject as an object that can have properties dynamically added and removed to it. Just cast it to an IDictionary (it implements that interface explicitly) and add the pairs. You can type the result as a dynamic or ExpandoObject based on whichever you prefer.
//I know this isn't the real type of your input;
//modify the parameter to be of the actual type of your collection of pairs
//TODO come up with better name for this function
public static dynamic Foo(IEnumerable<KeyValuePair<string,string>> pairs)
{
IDictionary<string, object> result = new ExpandoObject();
foreach (var pair in pairs)
result.Add(pair.Key, pair.Value);
return result;
}
Your query can then be modified to have:
Values = Foo(item.ArchiveFieldValues),
Also note that the query provider most likely won't be able to do anything with that translation, so you'll probably need to throw in an AsEnumerable before the select so that this projection is done in linq to objects.
I have a data table witch i serialize into a json and then parse to my view code where i use J Query to get those values.
When i use
document.getElementById('Name').value = UserInfo.Name;
the
Userinfo.Name = null,
what am i doing wrong for not being able to read my UserInfo.
Could someone please tell me how i can get the values out of UserInfo.
Below is all my code:
C# Code:
public JsonResult SearchForUser(int id)
{
string Sjson = JsonConvert.SerializeObject(DataTable, Formatting.Indented);
return Json(Sjson, JsonRequestBehavior.AllowGet);
}
J Query code:
$.post("SearchForUser", { id: id }, function (UserInfo) {
if (UserInfo != "")
{
document.getElementById('Name').value = UserInfo.Name;
document.getElementById('Surname').value = UserInfo.Surname;
}
});
Json :
"[ {
"UserId": 5,
"UserName": "JamesBond#MI6.com",
"UserPassword": "007",
"Name": "James",
"RoleId": 2,
"EmployeeId": 5,
"Active": true,
"Name1": "James",
"Surname": "Bond",
"IdNumber": "007",
"PassportNumber": "700",
"PhysicalAddress": "MI6",
"PostalAddress": "MI7",
"TelNumber": "0126659007",
"SelNumber": "0837777007",
"EmailAddress": "JamesBond#MI6.com",
"Designation": "Spy",
"DateEmployedFrom": "2013-06-19T00:00:00",
"Active1": true } ]"
Extra:
I am working with MVC razor.
Thanks in advance.
Edit still can't access values (This edits are in reply with answers)
It looks like your JSON object is an array with one item. In that case you should be accessing UserInfo[0].Name. Also verify that document.getElementById('Name') does indeed find an element.
Also, since you're using jQuery, document.getElementById('Name') = UserInfo[0].Name could be rewritten as $('#Name').val(UserInfo[0].Name).
Use var info=jQuery.parseJSON(UserInfo); to parse the value and then info.Name will give you result
DEMO
Like your JSON object structure Check here
I have a C# class which contains a property of Dictionary
I have a web-page which contains a list of items i need to cast into this dictionary.
My web-site will send the list up to my C# MVC application as JSON and then JsonConvert.Deserialise the JSON into my Dictionary object.
JsonConvert.Deserialise is expecting JSON in the following format:
"MyVariableName":{
"Item 1":true,
"Item 2":true
}
I need to know how i can construct this object in JavaScript.
So far, i have tried this without luck:
var items = [];
var v = $('#Items :input');
$.each(v, function(key, val) {
items.push({
key: val.value,
value: val.checked
});
});
JSON.stringify(v, null, 2);
But this returns a json converted value of:
"MyVariableName": [
{
"key": "Item 1",
"value": true
},
{
"key": "Item 2",
"value": true
}]
Which in turn does not de-serialize to my dictionary.
Thanks
Don't make an array; make an object:
var items = {};
$('#Items :input').each(function(i, val) {
items[val.value] = val.checked;
});
You have to use javascript serialization
One more thing you have different value int key, value pair like string and Boolean type, so you have to use Dictionary type.
And JavaScriptSerializerobject you will get System.Web.Script.Serialization name space of System.Web.Extensions.dll, v4.0.30319 assembly.
var jSerializer = new JavaScriptSerializer();
var newList= jSerializer.Deserialize<Dictionary<string,object>>(newData);