select Kendo ui grid row from controller - model-view-controller

My first problem is : I use kendo grid with Single Select mode and I need when view loaded for the first time, the first row is selected, in other words, i want to select the first kendo grid row programatically.
moreover other problem is i insert radiobutton column in that grid , and i want synchronize
radiobutton select with row select , in other words, i want that when user select row,it causes it's radiobutton Selected
Please help me
tnx
this is the code:
#(Html.Kendo().Grid<CommonData.Domain.LegalEntityPhone>()
.Name("SMSGrid")
.HtmlAttributes(new { style = "width:800px;" })
.Selectable(selectable =>
selectable.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
.Columns(columns =>
{
columns.Bound(c => c.Id)
.Title(" ")
.ClientTemplate(" <input type='radio' id='Approve' name='chkApprove' />");
columns.Bound(c => c.Number)
.Title("Destination")
.HeaderHtmlAttributes(new { style = "text-align: center;" })
.HtmlAttributes(new { style = "text-align: center; });
columns.Bound(c => c.CityCode)
.Title("City Code")
.Width(30)
.HeaderHtmlAttributes(new { style = "text-align: center" })
.HtmlAttributes(new { style = "text-align:center;width:30px" });
columns.Command(command => { command.Edit(); }).Width(150);
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Events(events => events.Change("OnChange"))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Id).Editable(false);
})
.Read(read => read.Action("LegalEntityPhoneInfo_Read", "Message"))
.Update(update => update.Action("LegalEntityPhoneInfo_Update", "Message"))
)
)

There is no such thing as making the row selected in the controller because the Grid is all created on the client. You can use the dataBound event to make the first row selected.
e.g.
$(function(){
$('#GridName').data().kendoGrid.bind('dataBound',function(e){
this.select(this.tbody.find('>tr:first'));
})
})
Or use one instead of bind to make the row selected only when the page is loaded, not each time when the Grid is rebound - sort,filter, etc. Check documentation for more info.

If you are unfamiliar with jQuery, I highly recommend you take an online free tutorial from http://jqueryair.com/.
Assuming your project is referencing the jQuery script in your _Layout page, all you should have to do is add an Event handler for Databound to the grid:
.Events(events => events.DataBound("Grid_Databound"))
Then just paste this script onto the page:
<script>
function Grid_Databound() {
var grid = $("#MyGridName").data("kendoGrid");
row = grid.tbody.find(">tr:not(.k-grouping-row)").eq(0);
grid.select(row);
}
</script>
I'm sure the same script that zeinad added would work as well, always more than one way to skin a cat. As far as making the radio button show selected if the row is selected, I think if you watched the tutorial I mentioned, you should be able to figure it out. Post back if you need more help.

Related

How do I display Kendo grids inside separate Kendo tabs of a tabstrip?

I'm trying to display two Kendo UI grids on two separate tabs of a Kendo tabstrip. It displays only the grid that is inside the tab with selected option being true. Here is my code:
#(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(items =>
{
items.Add().Text("Tickets")
.Selected(true)
.Content(
#<text>#(Html.Kendo().Grid((IEnumerable<Bugger.Models.Ticket>)ViewBag.Tickets)
.Name("grid2")
.Columns(columns =>
{
columns.Bound(tickets => tickets.TicketID);
columns.Bound(tickets => tickets.Description);
})
.Pageable()
.Sortable()
)
</text>
);
items.Add().Text("Technicians")
.Content(#<text>#(Html.Kendo().Grid((IEnumerable<Bugger.Models.Technician>) ViewBag.Technicians)
.Name("grid1")
.Columns(columns =>
{
columns.Bound(technician => technician.UserID);
columns.Bound(technician => technician.FirstName);
})
.Pageable()
.Sortable()
)</text>);
}))
I got my solution working. For future reference, I'm posting here.
The problem was that although I included "kendo.all.min.js" into my layout file, "kendo.aspnetmvc.min.js" was not included, an in order for this to work properly, I had to include this second javascript file too.
I added it to my _Layout.cshtml file.

How to update Kendo Grid row from window

The set-up:
ASP MVC project
Kendo Grid in a view via Razor
Column custom command, calls...
JavaScript that opens Kendo window with refresh() URL to partial view as custom form
The form has an input type=button calling JavaScript
The barrier:
How to update the row (dataItem?) of Grid with new model (from window/form javascript). I am unable to get a handle to target dataItem. Select() is not applicable here because the row is not selected. Instead, a custom button event opens modal Grid Window having the fields and commands for update, close, etc..
I could use the native Edit of Grid, but what I am trying to accomplish is a way to have complete customization of a pop up window showing partial view that can be used to present CRUD actions.
BTW: Rationale for this is to optimize space in a grid row that would normally be consumed with unnecessary buttons for Editing, and Deleting, layed down by use of the Kendo native control properties. I feel this is better presented in a separate, details view, like a Model Grid Window, in my case.
Again, not using Select(), I am unable to understand how to get a handle, within the Window/form JavaScript, to the Grid row that it was called from, for purposes of updating the row with new model data.
Thanks for your time.
Using your method you are doing double request so my suggesting:
On edit open a window binded to row via MVVM :
function edit(e) {
//get the row which belongs to clicked edit button
var item = this.dataItem($(e.currentTarget).closest("tr"));
//bind the window to the item via mvvm http://docs.telerik.com/kendo-ui/framework/mvvm/overview
kendo.bind($("#window"), item);
}
The window contain an editor template (Shared/EditorTemplates/Client.cshtml) :
#(Html.Kendo().Window().Name("window")
.Title("Client Details")
.Visible(false)
.Modal(true)
.Draggable(true)
.Width(400)
.Content(#<text>
#Html.Partial("EditorTemplates/Client", new Product())
</text>))
//Put in every element in the window data-bind="value:INPUT NAME"
//<input name="price" /> become <input name="price" data-bind="value: price" />
$("#window [name]").each(function () {
var name = $(this).attr("name")
$(this).attr("data-bind", "value:" + name );
});
The editor template :
#model Product
#Html.TextBoxFor(m => m.Name)
This demo shows how to get reference of the dataItem bound to the column where the custom command key is pressed, and shows the respective info in a Window. You can use the dataItem to update the Grid as well:
http://demos.telerik.com/kendo-ui/grid/custom-command
Here is an example as well:
http://dojo.telerik.com/abUHI
Take a look at the showDetails function
My discoveries since posting this...
I'm new with web presentation development, therefore grasping the distinction of client vs. server side elements and scope of such was key point. As well, learning the various specifics of the Kendo Grid was also helpful.
Continuing on with my present solution...
Getting a handle on the row item selected from custom command event not done with Select() because row is not being selected. As previously stated in other posts, this was only a part of the needed work. In the custom command event handler JavaScript (seen again in full solution below):
var detailDataItem = this.dataItem($(e.target).closest("tr"));
MY SOLUTION:
In the parent window that hosts the Kendo Grid:
#* Declare modal Kendo Grid window control *#
#helper ClientGrid()
{
#(Html.Kendo().Grid<Purevision.Models.Person>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.FirstName).Width(100);
columns.Bound(c => c.LastName).Width(130);
columns.Bound(c => c.Email).Width(140);
columns.Bound(c => c.Phone).ClientTemplate("#= (data.Phone) ? formatPhoneNumber(data.Phone) : 'none' #").Width(130);
columns.Bound(c => c.Comments).Hidden().Width(140);
columns.Bound(c => c.UserId).Hidden();
columns.Bound(c => c.Id).Hidden();
columns.Command(command =>
{
command.Custom("Archive").Click("archiveCommand");
command.Custom("Detail").Click("detailCommand");
}).Width(90);
})
.ToolBar(toolbar => toolbar.Create())
.Selectable(s => s.Mode(GridSelectionMode.Single))
.Events(e => e.Change("onChange").DataBound("onDataBound").DataBinding("onDataBinding"))
.Scrollable()
.Sortable()
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("Edit"))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(c => c.Id))
.Create(create => create.Action("People_Create", "Clients"))
.Read(read => read.Action("People_Read", "Clients"))
.Update(update => update.Action("People_Update", "Clients"))
.Destroy(update => update.Action("People_Destroy", "Clients"))
)
)
}
#* Declare modal Kendo Grid window control; MUST be named 'detailWindow' as referenced by partial view script *#
#(Html.Kendo().Window().Name("detailWindow")
.Title("Client Details")
.Visible(false)
.Modal(true)
.Draggable(true)
.Width(400)
.Content(#<text>
#Html.Partial("_edit", new Person())
</text>
)
<script type="text/javascript">
function detailCommand(e) {
var window = $("#detailWindow");
var kWnd = window.data("kendoWindow");
var data = this.dataItem($(e.target).closest("tr"));
e.preventDefault();
kendo.bind(window, data);
kWnd.center().open();
}
</script>
In the partial view _edit.cshtml being presented in Kendo modal window:
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-4">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<input type="button" id="updateButton" value="Update2" class="btn btn-default" />
Wire up button event during form ready, which gets a handle to the grid control still in scope on the client-side:
<script type="text/javascript">
// as mentioned by Tarek, bind each control's value attribute
$("#detailWindow [name]").each(function () {
var name = $(this).attr("name");
$(this).attr("data-bind", "value:" + name );
});
$(document).ready(function (e) {
var window = $("#detailWindow");
var grid = $("#grid").data("kendoGrid");
$("#updateButton").click(function (e) {
grid.saveChanges();
window.data("kendoWindow").close();
});
});
</script>
I'm open to refactoring suggestions here. It seems like lots of client-side coding in JavaScript to accomplish custom activity against the Kendo Grid. (sigh) I am happy to have the versatility though. (smile)
It took much re-editing to hopefully get this answer to something useful. Let me know. ;)
REFERENCES:
Telerik Forums / Kendo UI Forum / Grid / How does Grid update its dataSource?

Kendo grid virtual scrolling (endless scrolling) does not work

I want to turn on the endless scrolling on a kendo grid, called in this framework as virtual scrolling.
Abstract:
1) I load the page => the Action Virtualization_Read is called (OK)
2) I scroll down the Grid till bottom => the Action Virtualization_Read is called anothter time in order to get more data (KO)
The result is that when I reach the bottom of the grid, with scrollbar, the Action method that retrives the data is not hit anymore.
This is my grid, it shows the traces generated in my application:
#(Html.Kendo().Grid<Credit.Entity.ServiceObjects.MsgBlock>(Model.ListadoTrazas)
.Name("grdTrazas")
.Columns(columns =>
{
columns.Bound(c => c.LogID).Filterable(true);
columns.Bound(c => c.Timestamp).Filterable(false);
columns.Bound(c => c.FormattedMessage).Filterable(false).Width("80%");
})
.Scrollable(s => s.Virtual(true))
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.ServerOperation(true)
.Read(read => read.Action("Virtualization_Read", "Logging"))
)
)
And this is the MVC3 Action that fetches the data. This Action is called only the first time, when the page is loaded:
public ActionResult Virtualization_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(GetData(request.Page, request.PageSize).ToDataSourceResult(request));
}
[NonAction]
private List<MsgBlock> GetData(int page, int getCount)
{
MVCLogging model = new MVCLogging();
// Fetches the data
return model.ListadoTrazas;
}
The Model MsgBlock has the same properties defined in the Grid Columns method:
LogId
TimeStamp
FormattedMessage
Do I forget anything?
The only potential issue I see here is that you are leveraging server operations on the grid, but initializing the grid with a collection of data instead of letting it fetch the initial data. In the Kendo demo for virtualization using the MVC extensions, the grid definition looks like:
#(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(o => o.OrderID).Width(60);
columns.Bound(o => o.CustomerID).Width(90);
columns.Bound(o => o.ShipName).Width(220);
columns.Bound(o => o.ShipAddress).Width(280);
columns.Bound(o => o.ShipCity).Width(110);
columns.Bound(o => o.ShipCountry).Width(110);
})
.Sortable()
.Scrollable(scrollable => scrollable.Virtual(true))
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.Read(read => read.Action("Virtualization_Read", "Grid"))
)
)
Notice that after the type is supplied (Kendo.Mvc.Examples.Models.OrderViewModel) there is no initial set of data supplied, whereas your initialization attempts to give the grid the data it needs to render (Model.ListadoTrazas). Perhaps this is confusing the grid into thinking it has all the data is needs? I would try taking out Model.ListadoTrazas and letting the grid reach out for the data from the get go.

Adding a Dropdown inside Kendo Grid

I'm trying to add a DropDown inside kendo grid but it displays a TextBox
#(Html.Kendo().Grid((IEnumerable<Doc.Web.Models.Vendor.DocumentsDetails>)Model.documents_lst)
.Name("grid").Scrollable()
.Columns(columns =>
{
columns.Bound(o => o.DocumentRevisionID).Visible(false);
columns.Bound(o => o.Documentnumber).Title("Document #").Width(150);
columns.Bound(o => o.Revision).Title("Revision").Width(80);
columns.Bound(o => o.RevisionDate).Format("{0:dd/MM/yyyy}").Title("Rev Date").Width(85);
columns.Bound(o => o.RevisionStatus).Title("Revision</br> Status").Width(100);
columns.Bound(s => s.DocNumberPurpose).ClientTemplate((#Html.Kendo().DropDownList()
.BindTo((System.Collections.IEnumerable)ViewData["Purpose"])
.Name("DocNumberPurpose")
.DataTextField("Text")
.DataValueField("Value")
.ToClientTemplate()).ToHtmlString());
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(o => o.DocumentRevisionID))
.Model(model=>model.Field(o=>o.DocNumberPurpose).Editable(false))
)
.Events(ev=>ev.DataBound("onGridDataBound"))
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.DocumentRevisionID))
.Read(read => read.Action("EditingInline_Read", "DesignCoverSheet").Data("additionalInfo"))
)
)
<script>
function onGridDataBound(e) {
$('#grid script').appendTo(document.body);
}
</script>
You're very close actually:
columns.Bound(property => property.neatProperty).Width(38).EditorTemplateName("neatPropertyDropDownList").Title("NeatProperty")
And then in a separate view called "neatPropertyDropDownList.cshtml"
#using System.Collections;
#(Html.Kendo().DropDownList()
.Name("NeatProperty")
.DataTextField("Value")
.DataValueField("Text")
.BindTo("don't forget to bind!")
)
Check this article for a detailed example of exactly what you are trying to do, specifically in step 3
Step 3 – Embedding the Kendo Drop-down List
Basically you can do that in the following manner:
Inside the Kendo grid the property foreign key of your model must be linked to a EditorTemplateName that accepts a template name. As an example:
columns.Bound(e => e.CompanyId).EditorTemplateName("CompaniesList").Title("Company").ClientTemplate("#:CompanyName#");
The template name in the above example is "CompaniesList" which will be a cshtml view file inside EditorTemplates folder.
As per the above article:
The EditorTemplateName specifies to the grid that when either in Create or Edit modes, the template should be placed in the data file named "CompaniesList" that is found in the directory by name of EditorTemplates directory. The subsequent step therefore involves the creation of a folder by name of "EditorTemplates" and place an empty view in it by name of "CompaniesList". The code bit "ClientTemplate(“#:CompanyName#”)" means that when display is in the view mode, (that is, not creating or editing) CompanyName has to be displayed (in this case, it is "Microsoft"). Once this is complete, all what remains to be done is the creation of drop-down list which will be used in the view.
After you create the "CompaniesList" editor template file, you define the Kendo drop down list inside it as follows:
#using System.Collections
#model System.Int32
#(Html.Kendo().DropDownList()
.BindTo((IEnumerable)ViewBag.Companies)
.OptionLabel("- Select Company - ")
.DataValueField("Id")
.DataTextField("Name")
.Name("CompanyId")
)
Note that the drop down Name must be exactly as the column property in the grid which is "CompanyId"
You might look into Kendo Grid ForeignKey Column concept. It can be used as
columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "CategoryID", "CategoryName").Title("Category").Width(150);
Detail can be found here http://demos.telerik.com/kendo-ui/web/grid/foreignkeycolumn.html

Telerik mvc grid and fixed width column

all my grids will have in the first column, some image links to edit, delete and open the record.
I can't get this column to be fixed at 80 pixels.
Here is my code:
#(Html.Telerik().Grid(Model)
.Name("Grid")
.DataKeys(keys => keys.Add(c => c.Handle))
.DataBinding(dataBinding => dataBinding
.Ajax()
.Select("AjaxPesquisar", "Especialidade")
.Update("AjaxAtualizar", "Especialidade")
.Delete("AjaxDelete", "Especialidade"))
.HtmlAttributes(new { #class = "grid-padrao" })
.ClientEvents(events => events
.OnDataBound("atualizarCss")
)
.Columns(columns =>
{
columns.Template(#<span><a class="formatacao" href="/Especialidade/Details/238" image="show"></a><a class="formatacao delete-link" href="/Especialidade/AjaxDelete/238" image="delete"></a><a class="formatacao" href="/Especialidade/Edit/238" image="edit"></a></span>).Width(80);
columns.Bound("Descricao").Title("Descrição");
columns.Bound("Handle").Title("Código");
})
.Pageable()
.Sortable()
)
Column widths work best if the table-layout CSS setting of the table is set to fixed. You can either make your grid Scrollable() or use the following CSS:
<style>
.t-grid table
{
table-layout: fixed;
}
</style>
You can find more info about tables here.
I have the same issue too! What I did to get it work is to add:
columns.Bound(o => o.YourColumn)
.HtmlAttributes(new{#style="display:inline-block;width:80px;" });
Hope this helps.

Resources