i have a div defined for my listview like this:
<div id="carrierList"></div>
Here is my script that defines the listview and its datasource ;
<script type="text/javascript">
$(document).ready(function () {
var t94StragglerCarriers = new kendo.data.DataSource({
transport: {
read: {
url: "/MenuTrain/T94StragglerCarriers",
dataType: "json"
},
schema: {
fields: {
id: { type: "string" },
val: { type: "string" }
}
},
pageSize: 5,
serverPaging : true
}
});
var carriers = $("#carrierList").kendoListView({
dataSource: t94StragglerCarriers,
selectable: true,
pageable : true ,
change: onChange,
template : kendo.template($("#carrierTemplate").html())
}).data("kendoListView");
function onChange() {
var index = carriers.select().index();
var item = carriers.dataSource.view()[index];
console.log("Item " + index + " selected. Guid = " + item.id);
}
});
Here is the template definition for my listview :
<script type="text/x-kendo-tmpl" id="carrierTemplate">
<div id='carrierListVal_#=val#_#=id#' class='k-textbox'>#=val#</div>
<br/>
Here is the action method on my controller :
public JsonResult T94StragglerCarriers( [DataSourceRequest] DataSourceRequest request)
{
return Json(t94RailcarRepository.CarriersWithStragglers(), JsonRequestBehavior.AllowGet);
}
Here is the json string returned by the server :
[{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"CHTT"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"CMO "},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"CTCX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"DBUX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"GATX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"MWCX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"NDYX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"PLMX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"TAEX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"TCIX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"TEIX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"TILX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"UP "},{"id":"ffbcdb6c-4d3a-45f6-8ef6-ada5f28ba44b","val":"MDXx"}]
My problem is that from the onChange event handler, when i try to get the index of the selected listview item, like so :
var index = carriers.select().index();
it is returned a value as if each field in the json string is an element. For example , the first object's id field would be index 0 , and it's val fiedl would be index 1. and so on. Can anyone see what i am doing wrong to get the index of the selected listview item? or is there something wrong with the json string i don't see?
Related
I had this schema in my kendo-ui datasource. Then I had custom button in my kendo grid located at (column > field), so my question how to get an id when I click on that custom button? I try
click: function(e) {
e.preventDefault();
var currentId = $(e.target).closest("venueConfigurationTypeID");
var id = this.dataItem(currentId);
//var item = this.dataItem.id; <-- return undefined
}
and it return me a null value.
....
schema: {
model: {
id: "venueConfigurationTypeID",
fields: {
venueConfigurationTypeID : { editable: false, nullable: true },
configurationType : { type: "string", validation: {required: {message: "Value Required"}}},
configurationTypeDescription : { type: "string", validation: {required: {message: "Value Required"}}}
}
}
},
....
Find the answer.
click: function(e) {
e.preventDefault();
var selection = $(e.target).closest("tr");
var rowData = grid.dataItem(selection);
var id = rowData.venueConfigurationTypeID;
console.log(id);
}
How does the model structure look like for Kendo TreeView, to bind remote data
We have a tree displaying system locations which have hierarchical structure. We use the following code:
C# code:
[HttpPost]
public async Task<ActionResult> GetChildrenAsync(long? parentId)
{
//retrieving location's children by parentId
//DTO has ChildrenCount field that shows how many children has any particular location
return new JsonResult
{
Data = locations.Select(x => new
{
LocationId = x.Id,
Name = x.Name,
HasChildren = x.ChildrenCount > 0
}),
MaxJsonLength = Int32.MaxValue
};
}
JS code:
var locationDataSource = new kendo.data.HierarchicalDataSource({
transport: {
type: "json",
read: {
url: "#Url.Action("GetChildren", "Location")",
type: "POST"
},
parameterMap: function (data) {
return { parentId: data.LocationId };
}
},
schema: {
model: {
id: "LocationId",
hasChildren: "HasChildren"
}
}
});
var kendoTree = $("#location-tree").kendoTreeView({
dataSource: locationDataSource,
dataTextField: "Name"
});
I have one kendo grid where i am calling databinding dynamically.
Below is the code:
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var _dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "/Dashboard/GetAttritionEmployeeDetailsWithColl",
dataType: "json",
contentType: "application/json"
},
parameterMap: function (options, operation) {
return JSON.stringify(options);
}
},
schema: {
data: "Data",
errors: "Errors",
total: "Total",
model: {
fields: {
Department: { type: "string" },
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
$("#grid").kendoGrid({
dataSource:_dataSource,
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field: "Department",
title: "Department"
}
]
});
});
</script>
</div>
and here is the function used in dashboard controller
public List<Entity.EmployeeHeadCountResponse> GetAttritionEmployeeDetailsWithColl(Entity.DashboardEmpRequest request)
{
try
{
employeeHeadCountResponseList = new List<Entity.EmployeeHeadCountResponse>();
DashboardServiceAgent client = new DashboardServiceAgent();
request.FlapName = "Attrition";
request.LoggedInStaffId = "33019";
request.RoleName = "Administrator";
client.GetDashboardEmpDetailsWithBytes(request, (s, e) =>
{
if (e.GetType() == typeof(Service.GetDashboardEmpDetailsWithBytesCompletedEventArgs))
{
Service.GetDashboardEmpDetailsWithBytesCompletedEventArgs err = (Service.GetDashboardEmpDetailsWithBytesCompletedEventArgs)e;
if (err.Error == null && err.Result != null)
{
List<Service.GenericCollection> GenColl = new List<Service.GenericCollection>();
byte[] compress = err.Result;
GenColl = PayloadHelper.CompressedBytesToObject(compress) as List<Service.GenericCollection>;
HierarchyCollection collection = new HierarchyCollection(GenColl);
ServiceResult = GenColl;
EmpCollection = collection;
var mylist = EmpCollection.ToList();
if (EmpCollection != null)
{
dict = new HierarchyCollection().FillForCategoryValues(GenColl);
Employee_Read(request2);
}
}
}
}
);
}
catch (System.Exception ex)
{
Common.InsertLogging(ex);
}
return employeeHeadCountResponseList;
}
so in this function it is getting return data from wcf services so this is asynchronous service first time it is providing null value and second time it is getting the value so whenever it is getting data i am calling Employee_Read function inside this function. but not able to display data in kendo grid.
Now my question is here do i have to call main function which is returning json??
Instead of using
public List<Entity.EmployeeHeadCountResponse> GetAttritionEmployeeDetailsWithColl(Entity.DashboardEmpRequest request)
use
public ActionResult GetAttritionEmployeeDetailsWithColl()
and Return Plain Json instead of kendoDataSourceResult as you're already converting it to kendo datasource in the JavaScript side You must use
return Json(employeeHeadCountResponseList)
this is more than enough.
I wrote this code to use kendo UI autocomplete. I need to show the title of the selected result in the textbox and keep the if in some hidden input, how can I get the id. it seems the select doesn't work.
$("[data-autocomplete]").each(function () {
var luurl = $(this).attr('data-lookupurl');
var thisElemt = $(this);
$(this).kendoAutoComplete({
minLength: 3,
separator: ", ",
dataTextField: "title",
select: function (e) {
var selectedOne = this.dataItem(e.item.Index());
console.log(kendo.stringify(selectedOne));
},
dataSource: new kendo.data.DataSource({
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: luurl,
dataType: "json",
parameterMap: function (data) {
return { title: thisElemt.val() };
},
schema: {
model: {
id: "id",
fields: {
id: { type: "id" },
title: { type: "string" }
}
}
}
}
})
});
});
There is a typo error, you should use: e.item.index() instead of e.item.Index() (index is lowercase).
So the select function would be:
select : function (e) {
var selectedOne = this.dataItem(e.item.index());
console.log(kendo.stringify(selectedOne));
},
and easier way is :
var autocomplete = $("#autoCompleteId").data("kendoAutoComplete");
console.log(autocomplete.listView._dataItems[0]);
you can access to select data item in autocomplete.listView._dataItems[0] object
you can use script
<script>
$(document).ready(function () {
$("#categories").change(function () {
var url = '#Url.Content("~/")' + "Limitations/ThanaByDistrict_SelectedState";
var ddlsource = "#categories";
var ddltarget = "#target";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$(ddltarget).val(data);
});
});
});
</script>
in controller like
// Get selected combox value
public JsonResult ThanaByDistrict_SelectedState ( Guid Sel_StateName )
{
JsonResult result = new JsonResult ( );
objects temp=db . objects . Single ( m => m . ob_guid == Sel_StateName );
result . Data = temp.ob_code;
result . JsonRequestBehavior = JsonRequestBehavior . AllowGet;
return result;
}
For details you can see this LINK
I have a partial view where I am showing a web grid depending upon a value selected from a page.
For drop down I have used
#Html.DropDownListFor(
x => x.ItemId,
new SelectList(Model.Items, "Value", "Text"),
new {
id = "myddl",
data_url = Url.Action("Foo", "SomeController")
}
)
For drop down item select I have used
$(function() {
$('#myddl').change(function() {
var url = $(this).data('url');
var value = $(this).val();
$('#result').load(url, { value: value })
});
});
and below is my action
public ActionResult Foo(string value)
{
SomeModel model = ...
return PartialView(model);
}
everything works good, but when I try doing a paging or sorting on my webgrid which is on my partial view I am showing a new window with the web grid.
I wanted to be able to sort and page on the same page without postback
Please help
The following example works fine for me.
Model:
public class MyViewModel
{
public string Bar { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Foo(string value)
{
var model = Enumerable.Range(1, 45).Select(x => new MyViewModel
{
Bar = "bar " + value + " " + x
});
return PartialView(model);
}
}
Index.cshtml view:
<script type="text/javascript">
$(function () {
$('#myddl').change(function () {
var url = $(this).data('url');
var value = $(this).val();
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { value: value },
success: function (result) {
$('#result').html(result);
}
});
});
});
</script>
#Html.DropDownList(
"id",
new[] {
new SelectListItem { Value = "val1", Text = "value 1" },
new SelectListItem { Value = "val2", Text = "value 2" },
new SelectListItem { Value = "val3", Text = "value 3" },
},
new {
id = "myddl",
data_url = Url.Action("Foo", "Home")
}
)
<div id="result">
#Html.Action("Foo")
</div>
Foo.cshtml partial:
#model IEnumerable<MyViewModel>
#{
var grid = new WebGrid(
canPage: true,
rowsPerPage: 10,
canSort: true,
ajaxUpdateContainerId: "grid"
);
grid.Bind(Model, rowCount: Model.Count());
grid.Pager(WebGridPagerModes.All);
}
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
columns: grid.Columns(
grid.Column("Bar")
)
)
Notice that I have used a GET request to refresh the grid instead of POST because this way the value query string parameter selected in the dropdown is preserved for future sorting and paging.