var CustomGrid = declare([Grid, Keyboard, Selection]);
var questionGrid = new CustomGrid({
store: questionCacheStore,
columns: [
editor({
label: "Questions",
field: "question",
editor: "text",
editOn: "dblclick",
sortable:true})
],
selectionMode: "single",
cellNavigation: false
}, "questions");
I am new to Dgrid. So, please do bear with me .
i was able to populate the dgrid with a JsonStore content. But when i click on the column 'Questions', it doesn't get sorted as in local data store.instead it shows an error Uncaught TypeError: Object [object Object] has no method 'sort'. Is it required to define such a method . If so, how and where should i define it ?
I am not the person to answer your J2EE question. I asked that question recently. The solution that I found was to inject the HttpServletRequest directly. This allowed me access to the query string parameters. From there I was able to get the sort direction (ascending, descending) and column to sort. Hopefully the snippets below will help.
Example Grid Setup
require(["dojo/store/JsonRest", "dojo/store/Memory", "dojo/store/Cache",
"dojo/store/Observable", "dgrid/OnDemandGrid", "dojo/_base/declare", "dgrid/Keyboard",
"dgrid/Selection", "dojo/domReady!"],
function(JsonRest, Memory, Cache, Observable, Grid, declare, Keyboard, Selection) {
var rest = new JsonRest({target:"/POC_Admin/rest/Subcategory/", idProperty: "subcatId"});
var cache = new Cache(rest, new Memory({ idProperty: "subcatId" }));
var store = new Observable(cache);
var CustomGrid = declare([ Grid, Keyboard, Selection ]);
var grid = new CustomGrid({
columns: {
subcatId: "ID",
name: "Name"
},
store: store
}, "grid");
grid.on("dgrid-select", function(event){
// Report the item from the selected row to the console.
console.log("Row selected: ", event.rows[0].data);
});
grid.startup();
});
Example Rest GET
#Context private HttpServletRequest servletRequest;
#GET
#Path("")
#Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public String getSubcategories(#QueryParam("name") String name) throws IOException {
//Respond to a QueryString value.
if (servletRequest.getQueryString() != null && servletRequest.getQueryString().length() > 0) {
String querystringKey = servletRequest.getQueryString();
System.out.println("QSKey = " + querystringKey);
System.out.println("Substr: " + querystringKey.substring(0, 4));
if (querystringKey.length()>4) {
if (querystringKey.substring(0, 4).contains("sort")) {
//We have the sort request.
}
}
}
//Return all results otherwise from your DAO at this point
}
Related
Datasource is defined as:
var KendoDataSource_EmployeeAutoCompleteByFirstName = {
serverFiltering: true,
serverPaging: true,
serverSorting: true,
pageSize: 10,
transport: {
read: {
url: '#Url.Action("GetEmployeesByFirstName", "Employee")',
dataType: "json"
}
}
};
AutoComplete is defined as:
function KendoGridFilterAutoComplete(element, kendoDataSource, textField) {
element.kendoAutoComplete({
minLength: 3,
filter: "startswith",
dataSource: kendoDataSource,
dataTextField: textField
});
}
When using a kendoAutoComplete widget, the filter which is send by the datasource is like:
filter[logic]=and&
filter[filters][0][value]=smith&
filter[filters][0][operator]=startswith&
filter[filters][0][field]=LastName&
filter[filters][0][ignoreCase]=true
The JSON response from the server looks like:
[
{"First":"Bill","LastName":"Smith"},
{"First":"Jack","LastName":"Smith"},
{"First":"ABC","LastName":"Smithy"}
]
This works fine, however as you can see I return multiple entries, so the kendoAutoComplete shows two the same entries (Smith) because the first-name differs.
So what I actually want is do distinct on the server, and return only the possible LastName, as an array of strings like this:
[
"Smith",
"Smithy"
]
However the kendoAutoComplete cannot handle this. It shows "undefined" or an error.
How to solve this ?
I've create the following code:
#region AutoComplete
public virtual IQueryable GetAutoComplete(KendoGridRequest request)
{
// Get filter from KendoGridRequest (in case of kendoAutoComplete there is only 1 filter)
var filter = request.FilterObjectWrapper.FilterObjects.First();
// Change the field-name in the filter from ViewModel to Entity
string fieldOriginal = filter.Field1;
filter.Field1 = MapFieldfromViewModeltoEntity(filter.Field1);
// Query the database with the filter
var query = Service.AsQueryable().Where(filter.GetExpression1<TEntity>());
// Apply paging if needed
if (request.PageSize != null)
{
query = query.Take(request.PageSize.Value);
}
// Do a linq dynamic query GroupBy to get only unique results
var groupingQuery = query.GroupBy(string.Format("it.{0}", filter.Field1), string.Format("new (it.{0} as Key)", filter.Field1));
// Make sure to return new objects which are defined as { "FieldName" : "Value" }, { "FieldName" : "Value" } else the kendoAutoComplete will not display search results.
return groupingQuery.Select(string.Format("new (Key as {0})", fieldOriginal));
}
public virtual JsonResult GetAutoCompleteAsJson(KendoGridRequest request)
{
var results = GetAutoComplete(request);
return Json(results, JsonRequestBehavior.AllowGet);
}
#endregion
Which returns a unique list of anonymous objects which look like { "LastName" : "a" }.
i have this code in my view which is in a loop which gives me two rows for console.log
var jqxhr = $.getJSON("<%= Url.Action("GetTrainingModulePoints" , "Home") %>", function (data) {
console.log(JSON.stringify(data));
});
<%: Html.GetQTip("training-module-id-" + module.TrainingModuleId , "With assesment" , "training-module-id-" + module.TrainingModuleId , Zinc.Web.Extensions.QTipPosition.Bottom, true, "Module Points") %>
in my controller:
public JsonResult GetTrainingModulePoints()
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
IEnumerable<DataModels.Training.UserTrainingPointsDataModel> modulePoints = ZincService.TrainingService.GetTrainingModulePoints(currentUser.UserId);
return Json(new { result = modulePoints}, JsonRequestBehavior.AllowGet);
}
each console.log gives:
LOG: {"result":[{"InteractionType":6,"Points":50,"Name":"China Incentive Program"},{"InteractionType":8,"Points":1,"Name":"China Incentive Program"},{"InteractionType":6,"Points":50,"Name":"India - Q2 Incentive "},{"InteractionType":8,"Points":100,"Name":"India - Q2 Incentive "},{"InteractionType":6,"Points":50,"Name":"China - Q2 Incentive"},{"InteractionType":8,"Points":3,"Name":"China - Q2 Incentive"}]}
LOG: {"result":[{"InteractionType":6,"Points":50,"Name":"China Incentive Program"},{"InteractionType":8,"Points":1,"Name":"China Incentive Program"},{"InteractionType":6,"Points":50,"Name":"India - Q2 Incentive "},{"InteractionType":8,"Points":100,"Name":"India - Q2 Incentive "},{"InteractionType":6,"Points":50,"Name":"China - Q2 Incentive"},{"InteractionType":8,"Points":3,"Name":"China - Q2 Incentive"}]}
how can i get the interactiontype,name and points seperate?
public static MvcHtmlString GetQTip(this HtmlHelper htmlHelper, string propertyName, string message, string propertyNameOverride = "", QTipPosition position = QTipPosition.Right, bool includeEvents = true, string title = "")
{
string qtipPosition = String.Empty;
switch (position)
{
case QTipPosition.Right:
qtipPosition = "my: 'left center', at: 'right center'";
break;
case QTipPosition.Left:
qtipPosition = "my: 'right center', at: 'left center'";
break;
case QTipPosition.Top:
qtipPosition = "my: 'top middle', at: 'bottom middle'";
break;
case QTipPosition.Bottom:
qtipPosition = "my: 'bottom middle', at: 'top middle'";
break;
}
if (!String.IsNullOrWhiteSpace(propertyNameOverride))
propertyName = propertyNameOverride;
if (String.IsNullOrWhiteSpace(title))
title = htmlHelper.Resource(Resources.Global.Title.Information);
StringBuilder sb = new StringBuilder();
sb.Append(String.Concat("$('#", propertyName, "').removeData('qtip').qtip({content: {text:"));
sb.Append(String.Concat("'", message, "', title: { text: '", title, "', button: false }}, position: { ", qtipPosition, " }"));
if (includeEvents)
sb.Append(", show: { event: 'focus mouseenter', solo: true, ready: false }, hide: 'blur'");
sb.Append(", style: { classes: 'ui-tooltip-shadow ui-tooltip-yellow' } });");
return new MvcHtmlString(sb.ToString());
}
}
public sealed class MvcHtmlString : HtmlString
{
}
Simply use the $.each() function:
var url = '<%= Url.Action("GetTrainingModulePoints" , "Home") %>';
var jqxhr = $.getJSON(url, function (data) {
$.each(data.result, function() {
var interactionType = this.InteractionType;
var name = this.Name;
var points = this.Points;
// do something with those variables ...
});
});
Here we are looping over the data.result collection in which each element represents an object having InteractionType, Points and Name properties according to the log you have shown. The $.each will obviously be executed for each element of the result collection.
UPDATE:
After the small discussion we had in the comments section it seems that you are doing something fundamentally wrong here. You are attempting to pass to a server side helper values that you have retrieved on the client using AJAX. That's impossible nr it makes any sense.
So you should be binding on the server. You shouldn't be doing any AJAX requests at all. You should simply call your server side helper and pass it the required parameters:
<%: Html.GetQTip(
"training-module-id-" + module.TrainingModuleId,
Model.Points,
"training-module-id-" + module.TrainingModuleId,
Zinc.Web.Extensions.QTipPosition.Bottom,
true,
"Module Points"
) %>
Now all you have to do is add this Points property to your view model:
public string Points { get; set; }
and inside the controller action that is rendering this view simply set this property. You would first query your data layer to retrieve an IEnumerable<UserTrainingPointsDataModel> and then perform some transformation on this array to convert it to a string that you want to be displayed:
MyViewModel model = ... get the view model from somewhere
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
var modulePoints = ZincService.TrainingService.GetTrainingModulePoints(currentUser.UserId);
model.Points = ... transform the original points collection to some string that you want to pass to the helper;
return View(model);
Remark: I don't know where you took this Html.GetQTip helper but looking at its source code I am horrified. This helper doesn't encode anything. Your site is vulnerable to XSS attacks. Never use any string concatenations to build up javascript and pass variables to functions.
I'd like to try ServiceStack's json parsing, but I've already figured out how to do something I need via Newtonsoft. Can this same thing by done via ServiceStack?
I've tried with the commented out code but it gives exceptions, see below for exception details.
Thanks!
Josh
[Test]
public void TranslateFromGitHubToCommitMessage()
{
const string json =
#"
{
'commits':
[
{
'author': {
'email': 'dev#null.org',
'name': 'The Null Developer'
},
'message': 'okay i give in'
},
{
'author': {
'email': 'author#github.com',
'name': 'Doc U. Mentation'
},
'message': 'Updating the docs, that\'s my job'
},
{
'author': {
'email': 'author#github.com',
'name': 'Doc U. Mentation'
},
'message': 'Oops, typos'
}
]
}
";
dynamic root = JObject.Parse(json);
//dynamic root = ServiceStack.Text.JsonSerializer.DeserializeFromString<JsonObject>(json);
//dynamic root = ServiceStack.Text.JsonObject.Parse(json);
var summaries = new List<string>();
foreach (var commit in root.commits)
{
var author = commit.author;
var message = commit.message;
summaries.Add(string.Format("{0} <{1}>: {2}", author.name, author.email, message));
}
const string expected1 = "The Null Developer <dev#null.org>: okay i give in";
const string expected2 = "Doc U. Mentation <author#github.com>: Updating the docs, that's my job";
const string expected3 = "Doc U. Mentation <author#github.com>: Oops, typos";
Assert.AreEqual(3, summaries.Count);
Assert.AreEqual(expected1, summaries[0]);
Assert.AreEqual(expected2, summaries[1]);
Assert.AreEqual(expected3, summaries[2]);
}
Exceptions Detail
When using the first commented out line:
dynamic root = ServiceStack.Text.JsonSerializer.DeserializeFromString<JsonObject>(json);
This exception occurs when the method is called.
NullReferenceException:
at ServiceStack.Text.Common.DeserializeListWithElements`2.ParseGenericList(String value, Type createListType, ParseStringDelegate parseFn)
at ServiceStack.Text.Common.DeserializeEnumerable`2.<>c__DisplayClass3.<GetParseFn>b__0(String value)
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2.<>c__DisplayClass7. <GetGenericEnumerableParseFn>b__6(String x)
at ServiceStack.Text.Json.JsonReader`1.Parse(String value)
at ServiceStack.Text.JsonSerializer.DeserializeFromString[T](String value)
at GitHubCommitAttemptTranslator.Tests.GitHubCommitAttemptTranslatorTests.TranslateFromGitHubToCommitMessage()
And, the second:
dynamic root = ServiceStack.Text.JsonObject.Parse(json);
var summaries = new List<string>();
foreach (var commit in root.commits) // <-- Happens here
'ServiceStack.Text.JsonObject' does not contain a definition for 'commits'
Note: the message is 'string' does not contain a definition for 'commits' if I use code from line one, but change the type to or to instead of
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at GitHubCommitAttemptTranslator.Tests.GitHubCommitAttemptTranslatorTests.TranslateFromGitHubToCommitMessage()
After using DynamicJson from .NET 4.0 ServiceStack
Referring to mythz's comment:
This test case works, but if I modify it like below:
var dog = new { Name = "Spot", Parts = new { Part1 = "black", Part2 = "gray" }, Arr = new [] { "one", "two", "three"} };
var json = DynamicJson.Serialize(dog);
var deserialized = DynamicJson.Deserialize(json);
Then, deserialized.Name and Parts are fine, but Arr is of type string.
Also:
If I use ' quotes it doesn't appear to work. Is that normal? json2 works (to the degree that Arr is also still a string), but json3 does not work at all. It just returns
Immediate Window:
deserialized = DynamicJson.Deserialize(json3);
{}
base {System.Dynamic.DynamicObject}: {}
_hash: Count = 1
----- code: -----
var json2 =
#"
{
""Name"": ""Spot"",
""Parts"": {
""Part1"": ""black"",
""Part2"": ""gray""
},
""Arr"": [
""one"",
""two"",
""three""
]
}";
var json3 =
#"
{
'Name': 'Spot',
'Parts': {
'Part1': 'black',
'Part2': 'gray'
},
'Arr': [
'one',
'two',
'three'
]
}";
var deserialized = DynamicJson.Deserialize(json1);
ServiceStack's JSON Serializer also supports dynamic parsing, see examples of how to parse GitHub's JSON in the Dynamic JSON section of the wiki page.
I'm, Having trouble passing JSON data into the Jstree.
Following is my Jstree
$("#tree")
.bind("open_node.jstree", function (event, data) {
console.log(data.rslt.obj.attr("id"));
})
.jstree({
"plugins" : ["themes", "json_data", "ui"],
"json_data" : {
"data": [{"data":'Top Level - ',"state":'closed',"attr":{"seq_no":341386}}],
"state" : "open",
"ajax": {
"type": 'POST',
"dataType": 'json',
"data": {"action": 'getChildren'},
"url": function (node) {
var nodeId = node.attr('seq_no');
return 'ajax/test.jsp?seq_no=' + 341386;
},
"success": function (new_data) {
return new_data;
}
}
}
});
And test.jsp looks like this:
RecordCollection result=null;
PlsqlSelectCommand selCmd = null;
String sErrorMsg = "";
String sqlSelect;
OutputFormat format = new OutputFormat( doc ); //Serialize DOM
StringWriter xmlOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer( xmlOut, format );
serial.serialize(doc);
JSONObject jsonObject = XML.toJSONObject(xmlOut.toString());
<%=jsonObject%>
The problem is JSON data isnt passed into the jstree. thus I cant set my children nodes. I've tried so hard but can't get this working.
Is there something else I need to do in order to pass this JSON string into the jstree.
My jstree works when the data feed is hard-coded.
Any help is much appreciated.
I am attempting to take the Name and ID fields from each object, but the fields are appearing undefined.
function OnHistoricalListBoxLoad(historicalListBox) {
$.getJSON('GetHistoricalReports', function (data) {
historicalListBox.trackChanges();
$.each(data, function () {
var listBoxItem = new Telerik.Web.UI.RadListBoxItem();
listBoxItem.set_text(this.Name);
listBoxItem.set_value(this.ID);
historicalListBox.get_items().add(listBoxItem);
});
historicalListBox.commitChanges();
});
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetHistoricalReports()
{
List<HistoricalReport> historicalReports = DashboardSessionRepository.Instance.HistoricalReports;
var viewModel = historicalReports.Select(report => new
{
ID = report.ID,
Name = report.Name
}).ToArray();
return Json(viewModel, JsonRequestBehavior.AllowGet);
}
I know that I am returning the data successfully, and I know that there is valid data. I am new to MVC/JavaScript, though.. I checked case sensitivity to ensure that I wasn't making just an easy mistake, but it does not seem to be the issue. Am I missing something more complex?
Inspecting the HTTP Response JSON tab in Chrome I see:
0: {ID:1, Name:PUE}
1: {ID:2, Name:Weight}
2: {ID:3, Name:Power Actual vs Max}
3: {ID:4, Name:Power Actual}
No idea, but passing such behemoth domain models to views is very bad practice. This is so kinda domain polluted that it has nothing to do in a view. In a view you work with views models. View models contain only what a view needs. In this case your view needs an ID and a Name. So pass a view model with only those single simple properties to this view:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetHistoricalReports()
{
var reports = DashboardSessionRepository.Instance.HistoricalReports;
var reportsViewModel = reports.Select(x => new
{
ID = x.ID,
Name = x.Name
}).ToArray();
return Json(reportsViewModel, JsonRequestBehavior.AllowGet);
}
Now, not only that you will save bandwidth, but you will get some clean JSON:
[ { ID: 1, Name: 'Foo' }, { ID: 2, Name: 'Bar' }, ... ]
through which you will be able to loop using $.each.
UPDATE:
Now that you have shown your JSON data it seems that there is a Content property which represents the collection. So you need to loop through it:
$.each(data.Content, ...);
and if you follow my advice about the view models your controller action would become like this:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetHistoricalReports()
{
var report = DashboardSessionRepository.Instance.HistoricalReports;
var reportsViewModel = report.Content.Select(x => new
{
ID = x.ID,
Name = x.Name
}).ToArray();
return Json(reportsViewModel, JsonRequestBehavior.AllowGet);
}
and now loop directly through the returned collection:
$.each(data, ...);