I'm using the Kendo UI scheduler with the timeline view and I need to populate the left column with data from my database. I'm struggling to understand how to do it.
The part I'm talking about is where in the demo appears:
resources: [{
field: "roomId",
name: "Rooms",
dataSource: [{
text: "Meeting Room 101",
value: 1,
color: "#6eb3fa"
}, {
text: "Meeting Room 201",
value: 2,
color: "#f58a8a"
}],
title: "Room"
}]
So instead of saying "meeting Room 101", I want it to load data from the server and the number of cells will vary, so the column will be dynamic.
Is this possible? Could someone point me to a good explanation on how to do it?
I don't know if the solution is still of interest to you, but intended for Google;)
You can use the Kendo DataSource:
var rooms = new kendo.data.DataSource({
transport: {
read: {
url: "/get/rooms",
dataType: "json"
}
}
and then just assign the datasource
resources: [
{
field: "roomId",
name: "Room",
dataSource: rooms,
title: "Room"
}
Model (Example):
public class RoomResourcesModel
{
public string text { get; set; }
public int value { get; set; }
public string color { get; set; }
}
Controller (Example):
public ActionResult Rooms()
{
var model = new List<RoomResourcesModel>();
model.Add(new RoomResourcesModel { text = "Room 1", value = "1", color = "#CD6600" });
model.Add(new RoomResourcesModel { text = "Room 2", value = "2", color = "#FF3030" });
model.Add(new RoomResourcesModel { text = "Room 3", value = "3", color = "#FFD700" });
return Json(model, JsonRequestBehavior.AllowGet);
}
Related
Used Kendo Version: 2015.2.624
I have implemented kendogrid server side paging with additional parameters. Below is how my controller looks like:
public ActionResult GetData([DataSourceRequest] DataSourceRequest request, DateTime startDate, DateTime endDate, int state = -1, string poolName = null, string submitter = null)
{
poolName = string.IsNullOrEmpty(poolName) ? null : poolName;
submitter = string.IsNullOrEmpty(submitter) ? null : submitter;
var summarylist = new List<Summary>();
var total = 0;
using (var db = new SummaryEntities())
{
var jobs = db.SummaryTable.Where(k => k.created >= startDate && k.created <= endDate)
.Where(k => state != -1 ? k.state == state : k.state > state)
.Where(k => poolName != null ? k.pool_name == poolName : k.pool_name != null)
.Where(k => submitter != null ? k.submitter == submitter : k.submitter != null);
jobs = jobs.OrderByDescending(job => job.id);
total = jobs.Count();
// Apply paging...
if (request.Page > 0)
{
jobs = jobs.Skip((request.Page - 1) * request.PageSize);
}
jobs = jobs.Take(request.PageSize);
foreach (var job in jobs)
{
summarylist.Add(new Summary(job));
}
}
var result = new DataSourceResult()
{
Data = summarylist,
Total = total
};
return Json(result, JsonRequestBehavior.AllowGet);
}
additional parameters are the current values which the user has set over the widget datepicker, input box etc.
Below is how my datasource looks like in grid:
<script type="text/javascript">
j$ = jQuery.noConflict();
j$(document).ready(function () {
j$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "/Home/GetData/",
dataType: "json",
data: {
startDate: j$("#startdate").val(),
endDate: j$("#enddate").val()
}
}
},
pageSize: 30,
serverPaging: true,
schema: {
data: 'Data',
total: 'Total'
}
},
height: j$(window).height() - 85,
groupable: true,
sortable: true,
filterable: false,
columnMenu: true,
pageable: true,
columns: [
{ field: "JobId", title: "Job Id", template: '#:JobId#', type: "number" },
{ field: "Name", title: "Job Name", hidden: true },
{ field: "PoolName", title: "Pool Name" },
{ title: "Date Time", columns: [{ field: "Start", title: "Start" },
{ field: "End", title: "End" }
],
headerAttributes: {
"class": "table-header-cell",
style: "text-align: center"
}
},
{ field: "State", title: "State" },
{
title: "Result", columns: [{ field: "ResultPassed", title: "P" },
{ field: "ResultFailed", title: "F" }
],
headerAttributes: {
"class": "table-header-cell",
style: "text-align: center"
}
},
{ field: "Submitter", title: "Submitter" }
]
});
});
</script>
It works pretty good until I observed this issue:
Change the filter values i.e submitter, date range etc and
controller gets all this information in additional parameters where
I am taking action accordingly and it works just fine.
Now suppose the result returned from step 1 has multiple pages and
when you click next page, or last page or any other page number, the
controller gets invoked which is expected but the additional
parameters being set in step 1 is not getting passed again instead
the default values are there which is ruining everything.
Correction:
Additional parameters are getting lost at client side only.
Now please tell me what am I missing here?
Expected Result: In step 2 additional parameters should not get lost and it should be same as step 1.
Any help is appreciated.
EDITED:
Complete controller and grid code.
Thanks,
Vineet
I got the solution from telerik support team:
Reply:
The described undesired behavior can be caused by the fact that the additional parameters:
data: {
startDate: j$("#startdate").val(),
endDate: j$("#enddate").val()
}
... are set to objects, instead of a functions. If they are set as functions, the values of the corresponding inputs will be evaluated every time read() is called, and the current values will be passed (like shown in the second example in the API reference):
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport.read.data
I have Kendo Grid, inside which I have dropdown input [editable]. Now I want to filter the values in dropdown based on value present in row next to it. For ex:
_________________________________________
Column 1 | Column 2 (this is a dropdown)
_________________________________________
A | Show only values relevant to A
__________________________________________
B | Show values relevant to B
_____________________________________________
C | Show values relevant to C
_________________________________________
you can do the following
On editing the row get the name from the first column
filter the second column based on the first column value
In the given sample below, I edited an existing sample provided by the Kendo UI for cascading dropdowns, so I wrote extra codes to get the Id of the first column, so in your case you can exclude the additional steps
The HTML needed
<div id="grid"></div>
The scripts needed
<script>
// array of all brands
var brands = [
{ brandId: 1, name: "Ford" },
{ brandId: 2, name: "BMW" }
];
// array of all models
var models = [
{ modelId: 1, name: "Explorer", brandId: 1},
{ modelId: 2, name: "Focus", brandId: 1},
{ modelId: 3, name: "X3", brandId: 2},
{ modelId: 4, name: "X5", brandId: 2}
];
$("#grid").kendoGrid({
dataSource: {
data: [
{ id: 1, brandId: 1, modelId: 2 }, // initial data item (Ford, Focus)
{ id: 2, brandId: 2, modelId: 3 } // initial data item (BMW, X3)
],
schema: {
model: {
id: "id",
fields: {
id: { editable: false }, // the id field is not editable
brandId: {editable: false}
}
}
}
},
editable: "inline", // use inline mode so both dropdownlists are visible (required for cascading)
columns: [
{ field: "id" },
{
// the brandId column
title: "Brand",
field: "brandId", // bound to the brandId field
template: "#= brandName(brandId) #", // the template shows the name corresponding to the brandId field
},
{
//The modelId column
title: "Model",
field: "modelId", // bound to the modelId field
template: "#= modelName(modelId) #", //the template shows the name corresponding to the modelId field
editor: function(container) { // use a dropdownlist as an editor
var input = $('<input id="modelId" name="modelId">');
input.appendTo(container);
input.kendoDropDownList({
dataTextField: "name",
dataValueField: "modelId",
//cascadeFrom: "brandId", // cascade from the brands dropdownlist
dataSource: filterModels() // bind it to the models array
}).appendTo(container);
}
},
{ command: "edit" }
]
});
function brandName(brandId) {
for (var i = 0; i < brands.length; i++) {
if (brands[i].brandId == brandId) {
return brands[i].name;
}
}
}
function brandId(brandName) {
for (var i = 0; i < brands.length; i++) {
if (brands[i].name == brandName) {
return brands[i].brandId;
}
}
}
function modelName(modelId) {
for (var i = 0; i < models.length; i++) {
if (models[i].modelId == modelId) {
return models[i].name;
}
}
}
// this function will be used by the drop down to filter the data based on the previous column value
function filterModels()
{
// bring the brand name from previous column
var brandName = $('#modelId').closest('td').prev('td').text();
// additional work in this sample to get the Id
var id = brandId(brandName);
// filter the data of the drop down list
var details= $.grep(models, function(n,i){
return n.brandId==id;
});
return details;
}
</script>
here a working demo
hope it will help you
I have a Kendo DropDownList, but strangely enough I can not set its initial value.
Html.Kendo().DropDownList()
.Name("PersonalCoachName")
.BindTo(new SelectList((List<string>)ViewData["coachResources"]))
.HtmlAttributes(new { style = "font-size:8pt;" })
ViewData["coachResources"] is a List of string type. Regardless I use
.BindTo(new SelectList((List<string>)ViewData["coachResources"], "Default"))
or
.SelectedIndex(3)
DropDownList does not change it value and only display the 1st value in the list. I need help on this. Thanks.
The value works only in jquery, not in html helper. So it works in Jquery like
var dropdownlist = $("#PersonalCoachName").data("kendoDropDownList");
dropdownlist.value(coachId);
dropdownlist.refresh();
Use the Value-method. See example code below.
#(Html.Kendo().DropDownList()
.Name("DropDownListName")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(model.DropDownListItems)
.Value(model.Selected)
)
EDIT:
DropDownList needs to be bind to List<SelectListItem> and it can be initialized as seen below.
var items = new List<SelectListItem>
{
new SelectListItem { Text = "Item0", Value = "0" },
new SelectListItem { Text = "Item1", Value = "1" }
};
In addition, I would recommend to use MVVM to attach it to view.
public class DropDownViewModel
{
public String Selected;
public List<SelectListItem> DropDownListItems;
public DropDownViewModel(String selected, List<SelectListItem> dropDownListItems)
{
Selected = selected;
DropDownListItems = dropDownListItems;
}
}
Use the property 'index' while initializing the kendo combobox to set the Default value.
$("#fabric").kendoComboBox({
autoWidth: true,
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "Cotton", value: "1" },
{ text: "Polyester", value: "2" },
{ text: "Cotton/Polyester", value: "3" },
{ text: "Rib Knit", value: "4" }
],
filter: "contains",
suggest: true,
index: 3
});
There are two ways to set default value when initializing a kendo dropdown list.
$("#yourdropdownlist").kendoDropDownList({
dataTextField: "valueName",
dataValueField: "valueCode",
dataSource: [
{ valueName: "A", valueCode: "0" },
{ valueName: "B", valueCode: "1" }
],
//Method 1 -set index
//index: 0
//Method 2 - set default value and text
value: "0",
text:"行政区划"
});
This was my dropdown:
#(Html.Kendo().DropDownList()
.HtmlAttributes(new { style = "width:95%", id = "customerSelection" })
.Name("customers-dropdown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model)
.OptionLabel("Select Customer...")
)
I wanted to select the default option "Select Customer..." upon some function. I was able to do this using following code:
var dropdownBox = $("#customerSelection").data("kendoDropDownList");
dropdownBox.text("");
dropdownBox.value("");
I currently have a Kendo-UI grid. It has a few column where user can sort on, works great. I also have a details link on each row, so if the user clicks on this they are taken to a details page. I need to pass the current sort into the details page as a value. How can I get the current sort? is there an event I can bind to?
Thanks
You can get the sorting configuration whenever you want using sort method.
Example: Being grid the id of your Grid. Do:
// Get the grid object
var grid = $("#grid").data("kendoGrid");
// Get the datasource bound to the grid
var ds = grid.dataSource;
// Get current sorting
var sort = ds.sort();
// Display sorting fields and direction
if (sort) {
for (var i = 0; i < sort.length; i++) {
alert ("Field:" + sort[i].field + " direction:" + sort[i].dir);
}
} else {
alert("no sorting");
}
I ran into this need today and learned that the event is now present as of 2016 R3 release (2016.3.914).
Example usage:
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" }
],
dataSource: {
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
],
schema: {
model: { id: "id" }
}
},
sortable: true,
sort: function(e) {
console.log(e.sort.field);
console.log(e.sort.dir);
}
});
</script>
See: http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-sort
I'm trying to place a DropDownList inside a WebGrid but I can't figure out how to do it :(
Things I've tried:
grid.Column("Id", "Value", format: ((item) =>
Html.DropDownListFor(item.SelectedValue, item.Colors)))
and
grid.Column(header: "", format: (item => Html.DropDownList("Colors", item.Colors)))
and
grid.Column(header: "", format: Html.DropDownList("Colors"))
and various others but I couldn't get it to work.
Any help is much appreciated.
Model
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public SelectList Colors { get; set; }
public int SelectedValue { get; set; }
}
public class ColorViewModel
{
public int ColorID { get; set; }
public string ColorName { get; set; }
}
Controller
public ActionResult Index()
{
var colorList = new List<ColorViewModel>() {
new ColorViewModel() { ColorID = 1, ColorName = "Green" },
new ColorViewModel() { ColorID = 2, ColorName = "Red" },
new ColorViewModel() { ColorID = 3, ColorName = "Yellow" }
};
var people = new List<PersonViewModel>()
{
new PersonViewModel() {
Name = "Foo",
Age = 42,
Colors = new SelectList(colorList)
},
new PersonViewModel() {
Name = "Bar",
Age = 1337,
Colors = new SelectList(colorList)
}
};
return View(people);
}
View
#model IEnumerable<PersonViewModel>
#{
var grid = new WebGrid(Model);
}
<h2>DropDownList in WebGrid</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Age"),
grid.Column() // HELP - INSERT DROPDOWNLIST
)
)
<p>
<button>Submit</button>
</p>
}
grid.Column(
"dropdown",
format: #<span>#Html.DropDownList("Color", (SelectList)item.Colors)</span>
)
Also in your controller make sure you set the value and text properties of your SelectList and instead of:
Colors = new SelectList(colorList)
you should use:
Colors = new SelectList(colorList, "ColorID", "ColorName")
Also it seems a bit wasteful to me to define the same SelectList for all row items especially if they contain the same values. I would refactor your view models a bit:
public class MyViewModel
{
public IEnumerable<SelectListItem> Colors { get; set; }
public IEnumerable<PersonViewModel> People { get; set; }
}
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public int SelectedValue { get; set; }
}
and then:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// define the values used to render the dropdown lists
// for each row
Colors = new[]
{
new SelectListItem { Value = "1", Text = "Green" },
new SelectListItem { Value = "2", Text = "Red" },
new SelectListItem { Value = "3", Text = "Yellow" },
},
// this is the collection we will be binding the WebGrid to
People = new[]
{
new PersonViewModel { Name = "Foo", Age = 42 },
new PersonViewModel { Name = "Bar", Age = 1337 },
}
};
return View(model);
}
}
and in the view:
#model MyViewModel
#{
var grid = new WebGrid(Model.People);
}
<h2>DropDownList in WebGrid</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Age"),
grid.Column(
"dropdown",
format: #<span>#Html.DropDownList("Color", Model.Colors)</span>
)
)
)
<p>
<button>Submit</button>
</p>
}
UPDATE:
And since I suspect that you are not putting those dropdownlists for painting and fun in your views but you expect the user to select values inside them and when he submits the form you might wish to fetch the selected values, you will need to generate proper names of those dropdown lists so that the default model binder can automatically retrieve the selected values in your POST action. Unfortunately since the WebGrid helper kinda sucks and doesn't allow you to retrieve the current row index, you could use a hack as the Haacked showed in his blog post:
grid.Column(
"dropdown",
format:
#<span>
#{ var index = Guid.NewGuid().ToString(); }
#Html.Hidden("People.Index", index)
#Html.DropDownList("People[" + index + "].SelectedValue", Model.Colors)
</span>
)
Now you could have a POST controller action in which you will fetch the selected value for each row when the form is submitted:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the model variable will contain the People collection
// automatically bound for each row containing the selected value
...
}
..make my dropdown list to select a value from the list when it loads.The following works for sure. I have tried it out myself. Any questions keep me posted.
#Html.DropDownList("RejectReason", Model.SalesReasonList.Select(u => new SelectListItem
{
Text = u.Text,
Value = u.Value,
Selected = u.Value ==#item.RejectReason
}))