I am trying to pass a string from the kendo datasource, into a template within the grid, that is acting as the Print button. The button fires a function that opens a new link to the report server, and I need to pass a string value into the function, so that string value is then sent in the url.
I have it working if I send the datasource Id field, but if I try to send a string value (Physician), I get an 'Unexpected identifier' error. I have tried changing the coluns: field: to Physician, but get the same error.
EDIT: I can pass any int value, but it breaks if I try to send a string.
How do I pass a value other than the Id to my template?
schema: {
model: {
id: "Id",
fields: {
"ClinicName": { type: "string" },
"Physician": { type: "string" },
"Phone": { type: "string" },
"Fax": { type: "string" },
"Specialty": { type: "string" },
"Consent": { type: "date" }
}
}
},
pageSize: 10
});
function printForm(Physician) {
var stuid = $('#sisid').html().match(/\d+/);
var user = $('#user').val();
var sid = $('#sess').val();
window.open("http://#reportServer/ReportServer/Pages/ReportViewer.aspx?/SHPN/Treatment%20Form&rs:Command=Render&StudentId=" + stuid + "&SessionId=" + sid + "&CurrentUser=" + user + "&Physician=" + Physician);
};
$(document).ready(function () {
columns: [
{
field: "Id",
width: "38px",
title: "Print",
filterable: false,
sortable: false,
template: "<a class='change-image' href='javascript:void(0);' title='Print Treatment Form' onclick='printForm(#= Id #)'><img alt='Student Info' src='#Url.Content("~/Content/Images/printer-icon.png")' /></a>"
},
Since Physician is a string you are probably not correctly escaping it. Try defining the template as:
template: "<a class='change-image' href='javascript:void(0);' title='Print Treatment Form' onclick='printForm(\"#= Physician #\")'><img alt='Student Info' src='#Url.Content("~/Content/Images/printer-icon.png")' /></a>"
Check it here: http://jsfiddle.net/OnaBai/ZwXa2/
columns.Bound(m => m.Name).Title("Subsys #").ClientTemplate("#= Name #");
This is razor syntax, you can insert some arbitrary string like this 'stringValue'
Related
Hello I have an editor table and would like to design one column as a variable dropdown. The values for the dropdown come from the ControllerDrpDwn method implemented in the controller. How can i get this output as dropdown options?
editor = new $.fn.dataTable.Editor({
ajax: { url: "/Controller/EditorTable" , type: "POST"},
table: "#tbl",
fields: [{
label: "abc:",
name: "abc"
},{
label: "xyz:",
name: "xyz",
type: "select"
// option: Output from ControllerDrpDwn method
}]
});
This is the method:
public async Task<IActionResult> ControllerDrpDwn()
{
return Ok(await _context.Dropdownoptions.Where(x => x.Selectbezeichnung == "xyz").Select(x => new
{
name = x.Optionbezeichnung
}).ToListAsync());
}
If you write javascript codes in a Razor page, you can follow this code to get the result:
#{var options = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);}
editor = new $.fn.dataTable.Editor({
ajax: { url: "/Controller/EditorTable" , type: "POST"},
table: "#tbl",
fields: [{
label: "abc:",
name: "abc"
},{
label: "xyz:",
name: "xyz",
type: "select"
option: #Html.Raw(options)
}]
});
But in controller, you need to change the code like this:
public async Task<IActionResult> ControllerDrpDwn()
{
return Ok(await _context.Dropdownoptions.Where(x => x.Selectbezeichnung == "xyz").Select(x => new
{
label= x.Optionbezeichnung,
value='value of item comes here'
}).ToListAsync());
}
I'm new to kendo UI, I am trying to implement Kendo grid with Webapi, paging does not take any effect below is the code.
The API
public IList<Customer> GetCustomers(int take, int skip)
{
this.Customers = FillData.Customers;
this.Orders = FillData.Orders;
return Customers.Skip(skip).Take(take).ToList();
}
And the javascript
$(document).ready(function () {
var element = $("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: "/api/GridData/GetCustomers",
dataType: "json"
},
pageSize: 6,
serverPaging: true,
},
height: 600,
sortable: true,
pageable: true,
//detailInit: detailInit,
//dataBound: function () {
// this.expandRow(this.tbody.find("tr.k-master-row").first());
//},
columns: [
{
field: "FirstName",
title: "First Name",
width: "110px"
},
{
field: "LastName",
title: "Last Name",
width: "110px"
},
{
field: "Country",
width: "110px"
},
{
field: "City",
width: "110px"
},
{
field: "Title"
}
]
});
});
The same thing with the Odata service telerik has provided works well.
Well I wrote a blog post couple of months back - Kendo UI Grid - Server Side Paging, Filtering and Sorting. This should resolve your query. Major focus in the post is on sending the right parameters to the WebAPI. I have shown a sample grid and datasource code as well request and response objects sent to the WebAPI. Let me know if you need any explanations.
Edit: Posting it all here since link only is not appreciated.
The Grid
Below is a Kendo UI Grid declaration for which we will implement the server side manipulation.
$("#sampleGrid").kendoGrid({
columns: [
{ field: "ID", title: "ID", width: 50 },
{ field: "Label", title: "Label", template: "<span class='k-link bold' title='${Description}'>${Label}</span>" },
{ field: "Description", title: "Description" }
],
dataBound: function () { this.element.find('tbody tr:first').addClass('k-state-selected') },
pageable: {
refresh: true,
pageSizes: [10, 15, 20, 25]
},
resizable: true,
reorderable: true,
filterable: true,
groupable: true,
selectable: true,
sortable: true
});
The DataSource
The below DataSource sends a call to a server method, address to which is saved in svcSampleUrl and assigned to it in the "transport" property. There is no need to make an ajax call separately to fetch the data for the datasource,
Setting serverPaging, serverFiltering, and serverSorting as true enables the Kendo UI Grid DataSource to send server calls when any one of the following events are triggered by the user; change of page, change in filters, and change in sorting of a column.
var sampleDataSource = new kendo.data.DataSource({
transport: {
read: {
url: svcSampleUrl,
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
parameterMap: function (options) {
model.Take = options.take;
model.Skip = options.skip;
model.Sort = options.sort;
model.Filter = options.filter;
return kendo.stringify(model);
}
},
schema: {
data: "sampleDTOList",
// another way to accept the response if some particular values need processing
//data: function (response) {
// //some implementation with the response values
// return response.WorklistDTOList;
//},
total: "totalItems",
model: {
fields: {
ID: { type: "number" },
Label: { type: "string" },
Description: { type: "string" }
}
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true,
pageSize: 10,
});
The parameter map property allows us to send a set of default parameters along with our custom ones back to the server. The default parameters include "take", "skip", "sort", and "filter" that correspond to page size, amount of records to skip, sort criteria, and filter criteria array respectively. Since one may require to send other parameters as well, the default parameter values are set in the model that has other values. Kendo.stringify is applied to the model and returned as a complete request object.
Data and Total
The DataSource schema contains two properties; "data" and "total". Each of these are the names of attributes in the response object in which we expect our results. I have assigned "sampleDTOList" to the "data" property since my response object will contain the list of records under that name. Similarly, I have assigned "totalItems" to "total" property. The "total" property accepts a numerical value of the count of all records irrespective of how many are returned on the current page. That way the DataSource knows how many records there are in actual and how many pages to show.
Note: The model is not explored here and is just referenced as a place holder for any model that can be used.
The Request
The Request object contains the exact attributes as the default and custom parameters the DataSource is set to send to the server.
public class FilterDTO
{
public int Take { get; set; }
public int Skip { get; set; }
public List<SortCriteria> Sort { get; set; }
public List<FilterCriteria> Filter { get; set; }
public string ID { get; set; }
}
public class SortCriteria
{
public string field { get; set; }
public string dir { get; set; }
}
public class FilterCriteria
{
public string field { get; set; }
public string operator { get; set; }
public string value { get; set; }
}
The Server End
This is where we receive the call with all the parameters needed to manipulate the data. This is a simple method that can call a database stored procedure with all the parameters for the filtered results. The stored procedure should then return a dataset according to the given page size, amount of records to skip, sort criteria, filter criteria array and any other filter parameter that me have been sent by the model included in the call request. Page number though requires to be calculated from the information we have.
[HttpPost]
[ActionName("GetItems")]
public SampleResponse GetItems(FilterDTO filterDTO)
{
//Calling a different layer for the read operation based in the parameter values
return BusinessLayer.GetItems(filterDTO);
}
Page Number
Since we receive "take" and "skip" from client end of the application, calculating required paged number is easy from the information given. When we know page size and amount of records to skip, we can obtain the page number by applying the following rule:
pageNo = (skip + take) / take
The Response
The Response object contains the two attributes needed by the DataSource as mentioned before; one for the "data" and one for the "total" property of the schema.
public class SampleResponse : BaseResponse
{
private List<SampleItems> SampleDTOList;
public List<SampleItems> sampleDTOList
{
get { return SampleDTOList; }
set { SampleDTOList = value; }
}
public int totalItems { get; set; }
}
Here my snipet. I have two problems. First, i can't view selected item, after i select item in dropdown and save. Second, if create new item without select domain, it has wrong site code. Domain can't be zero because site_data not contains item with code 0;
Help me please
You don't see the selected item because you did not set selectable to true in the ListView.
You get value 0 for domain because you did not define a default value for site in your dataSource so being a number the default value is 0 and it is not important the fact that there is no 0 in the list of values that you provide (there is no such validation). So you should have it as:
document.provider_source = new kendo.data.DataSource({
pageSize: 6,
schema: {
model: {
id: "code",
fields: {
code: { editable: false, nullable: true },
site: { type: "number", defaultValue: 1 },
login: { type: "string" },
pass: { type: "string" }
}
}
},
data: provider_data
});
Where I set defaultValue for site to 1 (first value in the list).
Your code modified here: http://dojo.telerik.com/#OnaBai/Ihab
I am using Kendo UI to bind a datasource to the Kendo Grid. I am trying to find the best way to create a column in the grid that is not bound to the datasource.
Currently, I am creating a field in the datasource and using some javascript and jQuery to set the values of that column after the data is read from the remote endpoint.
Datasource:
schema: {
model: {
fields: {
blah: {},
empty_column: {}
}
}
}
Grid:
columns: {
field: "empty_column",
width: 100,
title: "Empty"
}
Javascript:
datasource.data[item].set("empty_column", computed_value);
All code edited for brevity, it all works fine.
My question: is there a way to set the defaultValue for this new, empty column which is not connected to the remote endpoint?
When I set:
empty_column: {defaultValue: "None"}
the grid still displays 'undefined', I think because it is not receiveing any data for that field in the read operation. Is there a way to set the defaultValue in the grid? I haven't seen any examples of this...
defaultValue applies when you create a record, not when it is going to be displayed.
You can do:
Option 1: use parse in schema.fields.fieldName that would be something like this.
model: {
fields: {
empty_column: {
type : "string",
defaultValue: "none",
parse : function (data) {
if (!data.empty_columns) {
data.empty_column = "none";
}
return data;
}
},
blah : { type: "number" }
}
},
Option 2: Use schema.parse for adding the extra field value.
schema: {
model: {
fields: {
empty_column: {type: "string", defaultValue: "none"},
blah : { type: "number" }
}
},
parse: function (response) {
$.each(response, function (idx, item) {
if (!item.empty_column) {
item.empty_column = "none";
}
});
return response;
}
}
Of course, (for both options) if you certainly know that there is no previous value in empty_column you might save the test condition and leave only the assignment.
I have a simple Sencha Touch 2.1 model class:
Ext.define('App.model.User', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'id', type: 'number', defaultValue: 0 },
{ name: 'first', type: 'string' },
{ name: 'last', type: 'string' },
{ name: 'email', type: 'string' },
{ name: 'lastUpdated', type: 'auto' }
]
},
fullName: function () {
var d = this.data,
names = [d.first, d.last];
return names.join(" ");
}
});
A collection of these models is in a store that I've configured to use sencha's Rest Proxy. When I add a new model to the store, and call the Sync method on the store, the new model is posted to a ASP.NET WebAPI Users controller and the following action is hit:
// POST api/Default1
public HttpResponseMessage PostUser(User user)
{
// this is a new user -- get rid of the ID
user.Id = 0;
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
The problem is that the a string is being sent as the ID for the model, so it's not passing the ModelState.IsValid check on the controller. This is what's actually getting sent up:
{"id":"ext-record-5","first":"c","last":"d","email":"e","lastUpdated":null}
Any idea why the id field is being set to a string? Also, any idea how I can tell the post action in the Users controller not to validate the id field (as it should be handling creating a new item, it makes sense for the server to create the ID for the new item, not the client).
This link helped me figure it out. The updated model should be:
Ext.define('App.model.User', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'id', type: 'auto', persist: false },
{ name: 'first', type: 'string' },
{ name: 'last', type: 'string' },
{ name: 'email', type: 'string' },
{ name: 'lastUpdated', type: 'auto' }
],
},
fullName: function () {
var d = this.data,
names = [d.first, d.last];
return names.join(" ");
}
});
You need to set idProperty on the model. The field for id should also be set to type auto. See documentation here.