kendo ui mvc grid custom cells based on data cell values - kendo-ui

i need to change style of grid cell based data value
columns.Bound(p => p.Status).Width(60).Filterable(ftb => ftb.Multi(true));
this column takes only two values "Open,Closed" i need to Add class="label label-success" When the value = Closed And class="label label-danger" When the value = Open
thank you

Please try with the below code snippet.
columns.Bound(c =>c.Status).Title("Status").ClientTemplate("#if(Status=='Open') {#" +
"<label class='label label-success'>#=Status#</label>" +
"# } else {# " +
"<label class='label label-danger'>#=Status#</label>" +
"# } #").Width(60).Filterable(ftb => ftb.Multi(true));
Let me know if any concern.

Related

Kendo Grid - Conditional ClientTemplate

I have the following client template in a Kendo grid:
.Columns(columns =>
{
columns.Bound(p => p.ID).ClientTemplate("<input id='#=data.ID#' type='checkbox' onclick='chkEntry(this)' />")
etc...
That works fine. I want instead to only show that input if data.CandidateCode is equal to 'CO1'.
This is one of my attempts:
.Columns(columns =>
{
columns.Bound(p => p.ID).ClientTemplate("#if (# #=data.CandidateCode# # == 'CO1') {#<input id='#=data.ID#' type='checkbox' onclick= chkEntry(this)' /> #}#")
It is my understanding that one may use hashtag (#) to indicate arbitrary javascript, as well as for literals and data values. Am I on the right track here? No matter how I try this syntax, I get an 'Uncaught Error: Invalid template' error.
Yeah, the hash syntax can be tricky. Once you start js with '#" you don't need to further escape variables. When you are in the markup like <input> you do. So try this without the comment lines:
columns.Bound(p => p.ID)
// Inside code no need to hashtag CandidateCode
.ClientTemplate("# if (CandidateCode == 'CO1') { #" + "
// Inside markup you do need hashtag
"<input id='#=ID#' type='checkbox' onclick='chkEntry(this)' />" +
"#}#")

JQuery Function Calling On Click Of Anchor Tag Inside Kendo Grid MVC

I created a column inside my kendo grid in mvc as follows with a anchor tags based on true or false of a field.
columns.Bound(c => c.IsMapped).Width(140).ClientTemplate(
"# if (IsMapped == true) { #" +
"<a href='DeleteMap?Id=#=Id#' class='btn btn-xs default'>UnMap </a>" +
"# } else { #" +
"<a onclick=\"Show(this);\" href='javascript:void(0);'
class='btn btn-xs default'> Map </a>" +
"# } #" );
The first anchor tag is working fine and invoking my controller action. But the second anchor tag is not invoking the java script function. My Java script function is as follows.
function Show(e) {
e.preventDefault();
alert('Test1');
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var wnd = $("#portal").data("kendoWindow");
wnd.refresh({
url: "Test",
data: { id: dataItem.Id, pvid: dataItem.PVId }
});
wnd.center().open();
};
when I look in the page source, the second anchor tag is rendered as follows that has no onclick attribute set.
<a class="k-grid-filter" href="javascript:void(0)"><span class="k-icon k-
filter"></span></a>
Anything wrong in my code? Thanks in advance
Personally this is what I would do for your template to make it easier to maintain and test.
Restructure your current template from the nested JavaScript in your razor code and pull it out into a separate function like so:
columns.Bound(c => c.IsMapped).Width(140).ClientTemplate("#=unMap(data)#");
then create the associated function:
function unMap(data){
var retString = '';
if(data.IsMapped === true) {
retString = 'UnMap ';
}
else {
retString = '<a data-map="'+ data.Id + '" href="#" class="btn btn-xs default"> Map </a>';
}
return retString;
}
then in the events config for the grid add this:
.Events(events => events.DataBound("onBoundData"))
then attach this JavaScript function:
function onBoundData(e) {
$("a[data-map]").on("click", function (me) {
me.preventDefault();
//do your Show(this) method in here
});
}
this will then bind the event to the links with the data-map attribute.
Hope this helps and if you have any follow up questions feel free to ask.
Instead of building anchor tag like this
onclick=\"Show(this);\"
change it to
onclick='Show(this);'
the following code worked for me. Here I am assigning a css class to anchor element and handling click event of anchor element using jquery based on css class.
#Html.ActionLink("UnMap", "DeleteMap", new { Id = #item.Id })
</text>).ClientTemplate(
"# if (IsMapped == true) " + #"{# <a href=""DeleteMap?
Id=#=Id#"">UnMap</a>" + "# } " +
#"else {# <a href=""\#"" class='myCommand'>Map</a>" + "# } #").Width(75);
Thats working for me
cshtml
columns.Bound(c => c.REQUESTNUMBER).Title("Request ID").ClientTemplate("#=urlMap(data)#").Width(140);
js
var urlMap = function(obj){
return "" + obj.REQUESTNUMBER + "";
}

How to access value of collection property of Model in ClientRowTemplate of KendoUI

#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.AirlineCode).Title("Airline");
columns.Bound(p => p.SegmentInfo[0].FareClass).Title("Fare Class");
}
.ClientRowTemplate(
"<tr>"+
"<td style =\"width: 130px\"><img src=\"/Content/themes/base/image/#=AirlineCode#.jpg\"/><span> #=AirlineName#</span></td>" +
"<td><div class=\"ClassType\"> //#=SegmentInfo[0].FareClass//# </div></td>"+"</tr>"
)
How should I write //#=SegmentInfo[0].FareClass//# section of could to get the value from Model Property SegmentInfo ,which is an class object and I need to access it's Property called FareClass which is string object.
Try to give the proper syntax to access this kind of object value.
Thanks in advance to my helper.
I am not sure how well it will work with an array but try.
.ClientRowTemplate(
"<tr>"+
"<td style =\"width: 130px\"><img src=\"/Content/themes/base/image/#=AirlineCode#.jpg\"/><span> #=AirlineName#</span></td>" +
"<td><div class=\"ClassType\"> #=SegmentInfo[0].FareClass# </div></td>"+"</tr>"
)
(Remove the // completely)

Telerik MVC Grid: Row specific content in a HtmlAttributes

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)

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

Resources