Telerik MVC Grid: Row specific content in a HtmlAttributes - telerik

Is it posible to use row specific content into HtmlAttributes?
I got this cell with its content (o.ArrivalTime), when i move my mouse over it i'll like it to show the content from a other element (o.Note) in a tooltip
I tried this but it will not accept the o.Note
columns.Bound(o => o.ArrivalTime)
.Title("Arrival Time")
.Template(o =>
{%><%=(o.ArrivalTime < Convert.ToDateTime("2000-01-01")) ? "?" : o.ArrivalTime.ToString()%><%})
.Width(140)
.HtmlAttributes(new {title = o.Note })
;

Rather than using HtmlAttributes, you can do this inside Template.
columns.Bound(o => o.ArrivalTime)
.Title("Arrival Time")
.Template(o =>
{%><div title="<%= o.Note %>"><%=(o.ArrivalTime < Convert.ToDateTime("2000-01-01")) ? "?" : o.ArrivalTime.ToString()%></div><%})
.Width(140)
;

Please take a look at the following example.
Grid - Server Templates
In this example the first column uses a templating mechanism to create the column. In similar way you can create a template for your column and then use the different columns while defining the template. Here is the code snippet from the demo:
<% Html.Telerik().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
//Template column. The grid displays the HTML defined by the argument.
columns.Template(c => {
%>
<img
alt="<%= c.CustomerID %>"
src="<%= Url.Content("~/Content/Grid/Customers/" + c.CustomerID + ".jpg") %>"
/>
<%
});
//Regular databound column. The grid displays the value of the CustomerID property.
columns.Bound(c => c.CustomerID);
})
.Render();
%>
Hope this was helpful to your question.
Lohith (Tech Evangelist, Telerik India)

Related

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?

Telerik MVC Grid in Razor view, GridCommand not populating

I have a telerik mvc grid in a Razor view. I am using custom server binding. My issue is that on paging and sorting the GridCommand object properties "Page", "PageSize" & "SortDescriptors" are not getting the correct value. The funny thing is that the exact same code works for an aspx view. Since this is a new view, I have started using "Razor".
My view is -
#(Html.Telerik().Grid((IEnumerable<Mitek.MobileImaging.AdminSite.Models.ImagingTransactionModel>)ViewData["DeficientGridView"])
.Name("DeficientImagesGrid")
.DataBinding(databinding => databinding.Server()
.Select("ViewDeficientImages", "SuperAdmin", new { orgId = ViewData["OrgId"], beginDate = ViewData["BeginDate"], endDate = ViewData["EndDate"], searchString = ViewData["SearchString"] }))
.DataKeys(keys => keys.Add(o => o.TranId))
.EnableCustomBinding(true)
.BindTo((IEnumerable<Mitek.MobileImaging.AdminSite.Models.ImagingTransactionModel>)ViewData["DeficientGridView"])
.Columns(
columns =>
{
columns.Template(
#<text>
<a href="#Url.Action("DeficientImageDetails", "SuperAdmin", new { id = item.TranId }) ">
<img alt="Deficient Image Details" src= "#Url.Content("~/Content/ImagesUI/detail_icon.gif")" style="border:0px" /></a>
</text>
).Title("Actions").Width(75);
columns.Bound(o => o.TranId).Hidden(true);
columns.Bound(o => o.user_email).Title("User Email").Width(250);
columns.Bound(o => o.xml_config_name).Title("Job File").Width(200);
columns.Bound(o => o.datetime_created).Title("Date Created").Format("{0:MM/dd/yyyy}").Width(200);
columns.Bound(o => o.short_note).Title("Note").Width(200);
columns.Bound(o => o.iqa_code).Title("IQA Code").Width(200);
}).HtmlAttributes(new { style = " font-family:arial; font-size: .9em; " })
.Sortable()
.Pageable(paging => paging.Position(GridPagerPosition.Bottom)
.Style(GridPagerStyles.NextPreviousAndNumeric)
.Total((int)ViewData["DeficientImagesCount"])
.PageSize(25))
)
The controller looks like
[GridAction(GridName = "DeficientGridView")]
public ActionResult ViewDeficientImages(DeficientImagesViewModel model, GridCommand command, string button)
{
//Some Code......;
GridCommand myCommand = new GridCommand() { PageSize = 25 };
}
The command object never has any values for command.Page, command.SortDescriptors at the time of paging or sorting. Please note that the exact same code works in a asps page.
Please help.
Thanks,
SDD
Can you check if it has to do with [GridAction(GridName = "DeficientGridView"] attribute and your grid name being different.Name("DeficientImagesGrid") ?
You have to change [GridAction(EnableCustomBinding = true, GridName = "DeficientImagesGrid")] to this. I have the same problem today and i found this is working. If you don't specify the GridName then you will not get GridCommand.
gridCommand is NOT populated when the query string parameters are QueueGrid-size=2&QueueGrid-page=3
gridCommand is populated when the query string parameters are size=2&page=3

cascading dropdownlist as bound column on telerik grid

I am not sure if anyone has ever come across an issue like this.
In my ASP.NET MVC application, I have a Telerik Grid control, which has the first 2 columns as dropdownlists. I have the editor template for each of these columns as telerik dropdownlists. These dropdownlists are in user control (.ascx) files. The code for the ascx files is below:
User Control 1:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%=Html.Telerik().DropDownListFor(m => m)
.BindTo(new SelectList((IEnumerable)ViewData["AccountTypeSelectList"], "lookUpCode", "description"))
%>
User Control 2:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%=Html.Telerik().DropDownListFor(m => m)
.BindTo(new SelectList((IEnumerable)ViewData["CreditAgenciesSelectList"], "description", "description"))
%>
The following is the code for my View where the Grid bound columns are:
#(Html.Telerik().Grid<DealerOfferBaseKPI>()
.Name("T_KPI_CA")
.DataKeys(key => key.Add(o => o.DealerOfferRuleDetailId))
.ToolBar(commands =>
{
commands.Insert().ButtonType(GridButtonType.ImageAndText).ImageHtmlAttributes(new { style = "margin-left:0" });
})
.Columns(columns =>
{
columns.Bound(o => o.AccountType).Title("Account Type").ClientTemplate("<#= AccountType #>").EditorTemplateName("AccountType");
columns.Bound(o => o.CreditAgency).Title("Credit Agency").ClientTemplate("<#= CreditAgency #>").EditorTemplateName("CreditAgency");
columns.Bound(o => o.PercentageAllowed).Title("Percentage Allowed");
columns.Bound(o => o.EffectiveDate).Title("Effective Date").EditorTemplateName("Date").Format("{0:MM/dd/yyyy}");
columns.Bound(o => o.ExpireDate).Title("Expire Date").EditorTemplateName("Date").Format("{0:MM/dd/yyyy}");
columns.Command(commands =>
{
commands.Delete().ButtonType(GridButtonType.BareImage);
}).Title("Actions");
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_SelectKPIBatchEditing", "DealerOfferManagement", new { filterType = "KPIcreditAgency" }).Enabled(true)
.Update("_SaveKPIBatchEditing", "DealerOfferManagement").Enabled(true);
})
.ClientEvents(ce => ce.OnSave("GridValidation"))
.Selectable()
.Scrollable()
.Pageable()
.Sortable()
)
I am trying to make these 2 dropdownlists as cascading. The values of the first dropdown are Residential, Commercial and Both. The values in the second dropdown are Equifax, Experian, TransUnion and Intelliscore. When I select residential in the first dropdown I want the second dropdown to show everything but not Intelliscore. For all other values of the first dropdown, I want all values of the second dropdown to show.
I am passing in the values of the 2 dropdowns by using 2 ViewData objects from my controller.
With the code shown, the values in the selectlist are displayed in the dropdowns just fine.
Any help is appreciated.
On the change clientevent of the first dropdown user javascript to add or remove element as explained here

Telerik Extensions for MVC grid OnRowSelect problem

I have a Telerik Extensions for ASP .Net MVC grid on my web page and, even though I've added the "Selectable" method to it, the OnRowSelect event is not getting triggered. It seems that the grid is not even responding to the "Selectable" method since my mouse pointer does not change to the hand when I'm hovering over the grid.
Here is the grid declaration:
<% Html.Telerik().Grid(Model.Students)
.Name("Students")
.DataKeys(keys =>
keys.Add(s => s.Id)
)
.Columns(columns =>
{
columns.Bound(s => s.CourseScore).ReadOnly();
columns.Bound(s => s.StudentName).ReadOnly();
columns.Bound(s => s.Points).ReadOnly();
columns.Template(s =>
{%>
<input name="GradeReleaseStatus" type="checkbox" value="<%=s.GradeRelease%>"
<%if (s.GradeRelease)
{%>
checked="checked"
<%}%>
/>
<%
}).Title("Release Grade");
})
.Selectable()
.ClientEvents(events => events.OnRowSelect("Activities.DisplaySingleGrade"))
.Render(); %>
Can anyone tell me what I'm missing or doing wrong?
Thanks.
Do you see a hover effect when you move the mouse over a grid row? If yes - then selection is working. If not - probably there is a JavaScript error in your page. If you don't see a JavaScript error make sure the grid initialization JavaScript is output. This needs a ScriptRegistrar component to be present after the grid declaration. Lastly you can try with a simpler script to see if the JavaScript event is raised:
events.OnSelect("onSelect")
<script>
function onSelect() {
alert("OnSelect");
}
</script>

Telerik Mvc Grid and sub-property like Contact.Name when the contact is null

i use telerik grid in an mvc project.
I have a 'complex' model that i don't want change and have a structure like this:
task
task.Contact
task.Contact.FirstName
in telerik grid i want to show all the task with the name of the Contact...but the contact CAN be null: in this case telerik return (rightly) an error for nullreferenceException, how can avoid this and display an empty value in the column?
columns.Bound(p => p.Contact.FullName).Title("Contact").Width(250);
tnx at all
You can do this by specifying the Template of the bound column:
columns.Bound(p => p.Contact.FullName)
.Template(p =>
{
%>
<%= (p.Contact != null ? p.Contact.FullName : "") %>
<%
}
.Title("Contact")
.Width(250);
Or you can use ClientTemplate:
columns.Bound(p => p.Contact.FullName)
.ClientTemplate("<#= Contact? Contact.FullName : '' #>");

Resources