I have got a Kendo Grid with editable records:
When the user clicks the edit button, a Kendo Window opens with a form to edit the record.
I am achieving this by filling the Kendo Window from a controller method that fetches the data of the selected record via webservice: <- this is what I want to avoid. Instead, I want to take the data straight out from the table and put it into the input fields inside the Kendo Window, without any additional processing or html calls. The data is already on the table, I just don't know how to send it to the Kendo Window inputs.
Here's some code:
The javascript function called after clicking the edit button:
function openEdit() {
var window = $("#editWindow").getKendoWindow();
window.refresh({
url: '#Url.Action("_EditForm", "Controller")'
});
window.center().open();
}
The view contains a partial view call:
#Html.Partial("_EditWindow")
The called partial view contains the Kendo Window:
#(Html.Kendo().Window()
.Name("editWindow")
.Modal(true)
.Events(e => e.Open("drawWindow").Close("refresh").Refresh("hideLoading"))
.Iframe(true)
.Visible(false)
.Title("Edit Record")
)
How can the data from the selected row of the table be passed to the Kendo Window?
EDIT
I know how to get the values from the selected record in javascript:
var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
I just don't know how to pass them into the Kendo Window inputs.
I came to a solution for my problem. I now send the selected model from the view to the controller. I use the fantastic JSON.stringify to achieve it.
function onChange() {
if (this.dataItem(this.select()) != null) {
var rowModel = this.dataItem(this.select());
// gets the model of the selected item in the grid
$.ajax({
url: 'sendGridRecord',
type: "POST",
data: JSON.stringify(rowModel),
contentType: 'application/json'
});
}
}
You can define a partial view as per the requirement and render that on a kendow window on edit button click.i.e
#(Html.Kendo().Window().Name("myWindow")
.Content(Html.Partial(#Url.Content("~/Views/_EditWindow.cshtml")).ToString())
.Visible(false).Title("XYZ").Modal(true).Actions(actions => actions
.Custom("custom")
.Minimize()
.Maximize()
.Close()
).Resizable().Draggable())
function openEdit() {
//Open the kendow window here.
//Get the seleceted item
var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
//populate the partial view fields using the selectedItem variable like
$('#name').val(selectedItem.Name);
}
You can use these two methods in order to pass the Kendo().Grid()'s selected row data:
Method I:
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
#(Html.Kendo().Button()
.Name("myBtn")
.HtmlAttributes(new { type = "button", #class = "k-primary k-button k-button-icontext", onclick = "callActionBySelectedRowId('#GridMaster')" })
.Content("Add New")
)
</div>
</text>);
})
function callActionBySelectedRowId(grid) {
var grid = $(grid).data('kendoGrid');
id = grid.dataItem(grid.select()).ID;
window.location.href = '#Url.Action("YourAction", "YourController")/' + id;
}
Method II:
View:
#(Html.Kendo().Grid<KendoMVCWrappers.Models.Person>().Name("persons")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(m => m.PersonID);
})
.Read(read => read.Action("GetPersons", "Home"))
.Update(up => up.Action("UpdatePerson", "Home"))
)
.Selectable(s => s.Mode(GridSelectionMode.Multiple))
.Columns(columns =>
{
columns.Bound(c => c.BirthDate);
columns.Bound(c => c.Name);
columns.Command(cmd => cmd.Edit());
})
.Pageable()
.Sortable()
)
<input type="button" id="btn" name="name" value="send to Server!" />
<script type="text/javascript">
$(function () {
$('#btn').click(function () {
var items = {};
var grid = $('#persons').data('kendoGrid');
var selectedElements = grid.select();
for (var j = 0; j < selectedElements.length; j++) {
var item = grid.dataItem(selectedElements[j]);
items['persons[' + j + '].Name'] = item.Name;
items['persons[' + j + '].PersonID'] = item.PersonID;
}
//If you want to pass single item parameter use this and comment out "for loop" & use the second "data" line below:
//var singleItem = grid.dataItem(selectedElements[0]);
$.ajax({
type: "POST",
data: items,
//data: { ID: singleItem.ID }, //for passing single item parameter
url: '#Url.Action("Test","Home")',
success: function (result) {
console.log(result);
}
})
})
})
Controller:
public ActionResult Test(Person[] persons)
{
return Json(persons);
}
Note: If the View called from Controller cannot be rendered use the javascript function as below by using window.location.href instead of $.ajax
<script type="text/javascript">
$(function () {
$('#btn').click(function () {
var items = {};
var grid = $('#persons').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
window.location.href = '#Url.Action("YourAction", "YourController")/' + item.ID;
})
})
</script>
Related
First time with MVC5 and Telerik... I am reading Active Directory and getting all the security groups to display in a TreeView. After an Admin is done selecting the Roles he/she shall press the Save Groups button and then the javascript is supposed to get all nodes and pass them to the controller. The controller will save to the database. I need to know how to access the datacontext for a given node. After I get the data context I can proceed to get all of the nodes context and pass it to the controller.
Kendo Treeview and Buttons:
#{
ViewBag.Title = "Configure";
}
#model IEnumerable<CMDB.Web.Models.AdminGroups>
<div>
<input id="save" type="button" value="Save Groups" onclick="SaveData()" />
<input id="return" type="button" value="Return" onclick="location.href='#Url.Action("Index", "Admin")'" />
#(Html.Kendo().TreeView()
.Name("treeview")
.Checkboxes(checkboxes => checkboxes
.Name("checkedFiles")
.CheckChildren(true)
)
.Events(events => events.Check("onCheck"))
.DataTextField("Name")
.AutoScroll(true)
.DataSource(source => source
.Model(model => model.Id("id").HasChildren("hasChildren"))
.Read(read => read.Action("GetActiveDircetoryGroups", "Configure"))
)
)
</div>
Javascript:
<script type="text/javascript" >
//show checked node IDs on datasource change
function onCheck() {
var treeView = $("#treeview").data("kendoTreeView");
var id = treeView.dataItem(e.node);
}
function SaveData() {
var AllSelectedNodes = new Array();
AllSelectedNodes = ($("#treeview .k-item input[type=checkbox]:checked").closest(".k-item"));
alert(AllSelectedNodes.join('\n'));
var myApiUrl = '#Url.HttpRouteUrl("DefaultAPI", new { controller = "AdminValues", action = "SaveSelectedAdmins"})';
var movies = $.ajax({
url: myApiUrl,
type: 'POST',
data: AllSelectedNodes
});
}
</script>
Controller:
[HttpPost]
public void SaveSelectedAdmins(IEnumerable<CMDB.Web.Models.AdminGroups> ag)
{
string Sids = string.Empty;
foreach (var s in ag)
{
var pc = new PrincipalContext(ContextType.Domain, "", "");//blank for security purposes
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Guid, s.id.Value.ToString());
if (s.id.Value.ToString() == gp.Guid.Value.ToString())
{
Sids = Sids + "," + gp.Sid;
}
}
using (var ctx = new Data.DBContext())
{
var d2 = (from d in ctx.Set<Entities.Config>()
where d.Property == "str"
select d).SingleOrDefault();
d2.Value = Sids;
ctx.SaveChanges();
}
}
Using $.post instead of $.ajax fixed the issue.
I have a listbox in view.
This Listbox use template
Listbox
<div id="UsersLoad" style="width: 50%">
#Html.EditorFor(i => i.Users, "UsersForEdit")
</div>
Template UserForEdit (Part of the code)
#model string[]
#{
if (this.Model != null && this.Model.Length > 0)
{
foreach(var item in this.Model)
{
listValues.Add(new SelectListItem { Selected = true, Value = item, Text = item });
}
}
else
{
listValues = new List<SelectListItem>();
}
}
<div class="field-#size #css">
<h3>#Html.LabelFor(model => model):</h3>
#Html.ListBoxFor(model => model, listValues, new { id = id })
</div>
In another view div "Users" is called.
function LoadUsersCheckBox() {
$("#UsersLoad").load('#Url.Action("LoadUsers", "User")' + '?idUser=' + idUser);
}
LoadUsers Controller
public JsonResult LoadUsers(int? idUser)
{
var users = Service.GetSystemUsers(idUser);
var model = users.Select(x => new
{
Value = x,
Description = x
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
The controller method returns what I want.
But instead of it select the items in the listbox it overwrites the listbox with only the text of found users.
How to mark the items in the listbox on the function LoadUsersCheckBox?
Sorry for my bad English
The jQuery load() method "loads data from the server and places the returned HTML into the matched element." Note the words "the returned HTML". See http://api.jquery.com/load/
To select existing items, you should try get() instead (http://api.jquery.com/jQuery.get/). In the success callback handler, you will need to parse the returned data to an array. Then use an iterator to go over the items in the listbox, and if they exist in the parsed array, mark them as selected. Something like:
$.get("action url", function(data) {
var users = $.parseJSON(data);
$("#UsersLoad option").each(function() {
var opt = $(this),
value = opt.attr("value");
opt.removeAttr("selected");
if (users.indexOf(value) > -1) {
opt.attr("selected", "selected");
}
});
});
I have a kendo grid with Model details on each row and i want to exchange values of two Objects when a button on a row is clicked.
For example: an Object of name "Activity1" has order number"1"
Object of name "Activity2" has order number "2"
I want to press a button on the row of Activity 1 which exchange the order numbers, so that Activity 1 would have order number "2" and Activity 2 would have order number "1".
I was able to get the details of The object of the row pressed on and change it for what i want but i am not able to get the details of the next row to change it as well, any help?
The code:
#(Html.Kendo().Grid<WEB02.ConfigurationModel.TestGrid>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(o => o.Name).Width(110);
columns.Bound(o => o.Type).Width(130);
columns.Command(command => {command.Destroy();
command.Custom("Higher Order").Click("HigherOrder");
});
})
.Sortable()
.Scrollable(scrollable => scrollable.Virtual(true))
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Multiple))
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.Name))
.PageSize(100)
.Read(read => read.Action("ActivityGrid", "Configuration"))
.Destroy("TestDelete", "Configuration")
.Events(events => events.Sync("sync_handler"))
)
.Pageable(pageable => pageable
.Refresh(true))
)
function
function HigherOrder(e) {
var tr = $(e.target).closest("tr"); // get the current table row (tr)
var item = this.dataItem(tr);
// get the date of this row
//console.log(item);
console.log(item.NodeId);
console.log(item.Type);
console.log(item);
var newOrder= parseInt(item.ActivOrderNo)+1;
var params = {
nodeID: item.NodeId + ".CONFIG.OrderNumber",
write: newOrder
};
console.log(newOrder);
var temp = {
url: "/Configuration/WriteAttribute",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
$.ajax(temp);
If you just want to get next row, you need to use row.index property.
To get current row index:
var grid = $('[name="Grid"]').data("kendoGrid");
var dataRows = grid.items();
var rowIndex = dataRows.index(grid.select());
To get data item by index use next code snipet:
var nextDataItem = grid.dataItems()[rowIndex+1];
I have a tab strip with two tabs. In the first tab I have a search text box and grid to show search results. When the user has found the item using the search box, they select the item in the grid and it switches tabs to the treeview and selects the item in the treeview (all these components are kendo ui mvc).
The search is working and the the treeview item is selected, however, it has not scrolled down to the item position in the view. Here is the code I have, but cannot get the scrolling working. I am using the jquery plugin scrollto.
Index.cshtml:
<body>
<div class="container-fluid">
<section style="padding-top:10px;"></section>
<div style="float:left; position:fixed">
#(Html.Kendo().TabStrip()
.Name("tabstrip")
.Events(events => events
.Activate("onTabActivate")
)
.Items(tabstrip =>
{
tabstrip.Add().Text("Search")
.Selected(false)
.Content(#<text>
<div>
<div style="padding-bottom:5px; padding-bottom:5px;">
<input type="text" class="clearable" id="search" name="search" placeholder="Enter a Account Name or Number" />
</div>
#(Html.Kendo().Grid<SageEMS.CRM.WebApp.DataService.AccountTreeItem>()
.Name("searchGrid")
.Events(events => events
.Change("onGridSelect"))
.Columns(columns =>
{
columns.Bound(acc => acc.AccountName);
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(w => w.Account))
.ServerOperation(false)
.Read(read => read.Action("LoadSearchResult", "Home").Data("searchAccounts"))
)
.Pageable()
.Selectable()
)
</div>
</text>);
tabstrip.Add().Text("Accounts")
.Selected(false)
.Content(#<text>
<div class='k-scrollable' style='height: 400px; overflow: auto;'>
#(Html.Kendo().TreeView()
.Name("treeview")
.Events(events => events
.Expand("onExpand")
.Select("onTreeviewSelect"))
.DataTextField("AccountName")
.DataSource(dataSource => dataSource
.Model(m => m
.Id("Account")
.HasChildren("HasChildren"))
.Read(read => read.Action("LoadAccountTree", "Home").Data("loadChildren"))
)
))
</div>
</text>);
})
)
</div>
<div id="dvSections" style="padding-left:450px;">
#{Html.RenderPartial("Sections", Model);}
</div>
</div>
<script>
var _selectedAccount = null;
var _selectedTrackingItem = null;
var _searchValue;
var _selectedGridItem = null;
var $search = $('#search');
var $treeview = $("#treeview");
var $searchGrid = $("#searchGrid");
var $txtSelectedAccount = $('#txtSelectedAccount');
var $tabstrip = $("#tabstrip");
$search.on('change keyup copy paste cut', function () {
// set delay for fast typing
setTimeout(function () {
_searchValue = $('#search').val();
$searchGrid.data("kendoGrid").dataSource.read();
}, 500);
});
$(function () {
$txtSelectedAccount.text("All");
$treeview.select(".k-first");
});
function searchAccounts() {
if (_searchValue) {
return {
searchTerm: _searchValue
};
}
}
function onExpand(e) {
_selectedAccount = $treeview.getKendoTreeView().dataItem(e.node).id;
$txtSelectedAccount.text(this.text(e.node));
}
function loadChildren() {
if (_selectedAccount) {
return {
id: _selectedAccount
};
}
}
function onTabActivate(e) {
var tab = $(e.item).find("> .k-link").text();
if (tab == "Search")
$search.focus();
if (tab == "Accounts") {
if (_selectedGridItem == null) return;
var dataItem = getTreeItem(_selectedGridItem.id);
if (dataItem)
selectNodeInTree(dataItem);
}
}
function onTreeviewSelect(e) {
_selectedAccount = $treeview.getKendoTreeView().dataItem(e.node).id;
$txtSelectedAccount.text(this.text(e.node));
}
function onGridSelect(e) {
var grid = $searchGrid.data("kendoGrid");
_selectedGridItem = grid.dataItem(grid.select());
var tabStrip = $tabstrip.kendoTabStrip().data("kendoTabStrip");
tabStrip.select(1);
// Get the tree item and select it
var dataItem = getTreeItem(_selectedGridItem.id);
if (dataItem)
selectNodeInTree(dataItem);
else
findExpandSearch(_selectedGridItem.id);
}
function getTreeItem(id) {
var treeView = $treeview.data('kendoTreeView');
var dataSource = treeView.dataSource;
var dataItem = dataSource.get(id);
return dataItem;
}
function findExpandSearch(id) {
// item is not loaded in treeview yet, find parent and trigger load children and search again
var url = "#Url.Action("LoadTreePath")";
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({ id: id }),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
if (data && data.length > 1) {
$.each(data, function (index, value) {
_selectedAccount = value;
loadChildren();
});
var dataItem = getTreeItem(data[0]);
if (dataItem)
selectNodeInTree(dataItem);
}
},
error: function (error, h, status) {
alert(error.responseText);
}
});
}
function selectNodeInTree(item) {
var treeView = $treeview.data("kendoTreeView");
var node = treeView.findByUid(item.uid);
if (node) {
treeView.select(node);
treeView.trigger("select", { node: node });
treeView.element.closest(".k-scrollable").scrollTo(treeView.select(), 450);
}
else
alert('Account not found in tree.');
}
</script>
<script src="../../Content/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</body>
</html>
I have used the following sample as a guide:
http://dojo.telerik.com/uYutu/23
Any suggestions appreciated, thanks in advance.
The example you posted works by scrolling the splitter's k-pane. The tabstrip you're creating your tree in doesn't have a k-scrollable, so you need to create your own scrollable container:
<div class='scrollable' style='height: 300px; overflow: auto;'>
<div id="treeview-left"></div>
</div>
and then scroll it
tree.element.closest(".scrollable").scrollTo(tree.select(), 150)
Also, I think triggering the select event shouldn't be necessary since the select method will do that for you.
(demo)
I had a similar problem in my Treeview setup which was close to yours and was using the scrollTo() much as described in Lars Höppner’s solution.
My problem turned out to be a height style that was being applied to my treeview. Having any height defined on the treeview breaks the scrollTo() operation.
Once I removed the offending css class it worked fine. Something to check for.
So right now I have a kendo grid where one of the columns has a checkbox for each row of data. Ultimately I want to be able to check and see which rows in the kendo grid have that check box checked, once a save button is clicked, and then store the contents of that row into an array/list so that I can send that data to the controller on an ajax call.
For example: My Kendo Grid has rows A, B, and C. If I hit the save button and only Row A is checked then I will store only Row A into an array.
Here is a snippet of the code that I currently have:
Razor
#(Html.Kendo().Grid(Model.ProgramVersions).Name("ProgramVersions")
.Columns(columns =>
{
columns.Bound(e => e.Code).Width(150);
columns.Bound(e => e.Description).Width(300);
columns.Bound(e => e.Linked).Width(150)
.Template(o => Html.CheckBox("Linked", o.Linked, o.Linked ? new {onclick = "return false"} : new {onclick = ""}));
})
.Pageable(p => p.PageSizes(new[] { 5, 10, 20 }))
.Scrollable(a => a.Height("auto"))
)
<button class="btnSubmit" type="button" onclick="submitLinkStartDateRequest()">Save</button>
Javascript
function submitLinkStartDateRequest() {
var programVersions = $("#ProgramVersions").data("kendoGrid").select();
var selectedProgramVersions = [];
programVersions.each(function() {
var programVersion = programVersions.dataItem($(this));
if ( /*something here*/) {
//add row from kendo grid to the selectedProgramVersions variable
}
});
$.ajax({
type: 'POST',
url: '/Lists/Controller',
dataType: 'json',
data: {
programVersions: selectedProgramVersions
}
});
}