I need to display two different values in the grid based on the Model Object property.I am able to do it using Template but not client template.
How to do it?
I have used the below code but i am getting error that IsContractORPO is undefined.
#{
Model.IsContractORPO = "P";
}
<div>
#{Html.Telerik().Grid(Model.TestList)
.Name("testGrid")
.Columns(columns =>
{
columns.Bound(col => col.FTE);
columns
.Template(#<text>#if (Model.IsContractORPO == "C")
{<div>#item.FTE</div>}
else if (Model.IsContractORPO == "P")
{<div>-</div>}</text>).Title("FTETestColumn")
.ClientTemplate("<# if (model.IsContractORPO == 'C') { #> <div><#=FTE#></div><# } else if(model.IsContractORPO == 'P'){ #><div>-</div><# } #>");
columns.Bound(col => col.BalanceAmount);
columns.Bound(col => col.BalanceUnits);
})
.ClientEvents(events => events.OnDataBinding("onDataBinding"))
.Render();
}
</div>
After sometime of analysis, i came to know that we can use a model property in the client template by making it as a script variable.
The following code solved the Issue.
<script type="text/javascript">
var isContractORPO = '#Model.IsContractORPO';
</script>
And the client template would be like
ClientTemplate("<# if (isContractORPO == 'C') { #> <div><#=FTE#></div><# } else if(isContractORPO == 'P'){ #><div>-</div><# } #>");
Related
I am trying to pass the column value. But it is not working and always saying "TrackingID" is undefined. I have spent lot of time in trying diff formats, but i feel i am missing something small. When i try to print the value of TrackingID in the column, it works fine. But when i try to pass this value into the function, it gives me the error saying "TrackingID is undefined"..
The below column is part of the child grid, which is present inside the kendo template like as follow:-
<script id="tplHistory" type="text/kendo-tmpl">
#(Html.Kendo().Grid<TrackingViewModel>()
.Name("HistoryGrid_#=PartnerGroupID#")
.Columns(columns =>
{
columns.Bound(v => v.PriceHigh).Title("Monthly High").Format("{0:c}").Width("12%");
columns.Bound(v => v.DateUpdated).Title("Edited Date").Format("{0:MM/dd/yyyy}").Width("10%");
columns.Bound(v => v.UpdatedBy).Title("Edited By").Width("10%");
columns.Bound(v => v.OperationName).Title("Status").Width("10%");
columns.Bound(v => v.TrackingID).HeaderTemplate(" ").ClientTemplate("#= revertTemplate(TrackingID) #");
})
Please help.
columns.Bound(v => v.TrackingID).HeaderTemplate(" ").ClientTemplate("#= revertTemplate(TrackingID)#");
function revertTemplate(tid) {
console.log(tid);
var markup = kendo.format("<i title='Revert the record' class='fa fa-floppy-o fontIcon' onclick=revertData({0})></i>", tid);
return markup;
}
function revertData(trackingid) {
alert(trackingid);
}
Try this:
columns.Bound(v => v.TrackingID).HeaderTemplate(" ").ClientTemplate("<a onclick=\"revertTemplate('#=TrackingID#')\">#=TrackingID#</a>");
Try to update your method as shown below (pass data and use data.PropertyName instead of just using PropertyName):
columns.Bound(v => v.TrackingID)
.HeaderTemplate(" ")
.ClientTemplate("#= revertTemplate(data)#");
function revertTemplate(data) {
console.log(data.TrackingID);
var markup = kendo.format("<i title='Revert the record' class='fa fa-floppy-o fontIcon' onclick=revertData({0})></i>", tid);
return markup;
}
function revertData(data) {
alert(data.TrackingID);
}
For more information have a look at How Do I Have Conditional Logic in a Column Client Template?
Hope this helps...
Finally i found the solution:-
columns.Bound(v => v.TrackingID).HeaderTemplate(" ")
.ClientTemplate("<i title='Revert the record' class='fa fa-floppy-o fontIcon' onclick='revertData(\\#:TrackingID\\#);'></i>");
I have three column in kendoui grid as "Delivery Location", "PickUp location" and "Available Shipping Options". When either of the location column changed("Delivery location" or "Pickup location"), the "Available shipping options" column should be changed accordingly.
I can achieve this using Cascade-from for two column(i.e. if one column changed, other would list the result based on the first column data) but don't know how to achieve same for two or more column.
How can i achieve cascading for two or more column?
Code:
JS Function:
function filterShippingOptions() {
return { pickUpLocationId: $("#PickUpLocationId").data("kendoDropDownList").value(), deliveryLocationId: $("#deliveryLocationId").data("kendoDropDownList").value() };
}
AvailableShippingOptions Editor:
#(Html.Kendo().DropDownListFor(m => m)
.DataValueField("ShippingOptionId")
.DataTextField("ShippingOptionName")
.OptionLabel("Select...")
.AutoBind(false)
.DataSource(dataSource =>
{
dataSource.Read(read =>
{
read.Action("GetAvailableShippingOptions", "ProductionZone").Type(HttpVerbs.Post)
.Data("filterShippingOptions");
}).ServerFiltering(true);
})
//.CascadeFrom("RMSupplierLocationViewModel")
.CascadeFrom("DeliveryLocationViewModel")
)
#Html.ValidationMessageFor(m => m)
There are two options to achieve what you are looking for:
Option 1: You can Use Cascading + Server Filtering
Option 2: You can Use Cascading + Client Side Filtering
First of all you will need to define events on both of your drop downs of Locations ("Delivery location" or "Pickup location") as below:
#(Html.Kendo().DropDownListFor(m => m)
.Name("PickUpLocationId")
.DataValueField("ShippingOptionId")
....
....
.Events(evnt=>evnt.Cascade("onCascade")) //Need to add this Event on Parent Drop Downs
)
Repeat the same for another Location DropDown. Your Cascade Event should be as below:
Server side filtering
#(Html.Kendo().DropDownListFor(m => m)
.Name("ShipingOption")
.DataValueField("ShippingOptionId")
.DataTextField("ShippingOptionName")
.OptionLabel("Select...")
.AutoBind(false)
.DataSource(dataSource =>
{
dataSource.Read(read =>
{
read.Action("GetAvailableShippingOptions", "ProductionZone").Type(HttpVerbs.Post)
.Data("filterShippingOptions");
}).ServerFiltering(true);
})
)
JS Function
function onCascade(e){
("#ShipingOption").data("kendoDropDownList").dataSource.read();
}
function filterShippingOptions() {
return { pickUpLocationId: $("#PickUpLocationId").data("kendoDropDownList").value(), deliveryLocationId: $("#deliveryLocationId").data("kendoDropDownList").value() };
}
Client side filtering
For Second option you will need to retrieve all the records for the Shipping option, disable server filtering to false and apply the filtering in the onCascade JS Function.
I have achieved this as follows:
View code:
<script>
function filterShippingOptions() {
return { locationId: $("#LocationViewModel").data("kendoDropDownList").value(), deliveryLocationId: $("#Location2ViewModel").data("kendoDropDownList").value() };
}
function onCascade(e) {
$("#ShippingOptionViewModel").data("kendoDropDownList").dataSource.read();
}
</script>
Editor code:
#model Comanex.Models.ShippingOptionsViewModel
#(Html.Kendo().DropDownListFor(m => m)
.DataValueField("ShippingOptionId")
.DataTextField("ShippingOptionName")
.OptionLabel("Select")
.AutoBind(false)
.DataSource(dataSource =>
{
dataSource.Read(read =>
{
read.Action("GetAvailableShippingOptions", "Shipping").Type(HttpVerbs.Post)
.Data("filterShippingOptions");
}).ServerFiltering(true);
})
)
#Html.ValidationMessageFor(m => m)
Controller Method:
public JsonResult GetAvailableShippingOptions(string PickUpLocationId, string DeliveryLocationId)
{
//Getting value from database
return Json(ShippingOptionRepository.GetAvailableShippingOptions(PickUpLocationId, DeliveryLocationId), JsonRequestBehavior.AllowGet);
}
Both the Parent controls(Dropdownlists in my case) should have following:
.Events(evnt => evnt.Cascade("onCascade")) //Need to add this Event on Parent Drop Downs
I've created a grid with a dynamic object and I'd like to use the GridEditMode.InLine to update and add data. The popUp mode is working but with the InCell and
the inline I'm getting the following error:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Am I missing something?
I tried to use a custom template but I am still getting the same error.
Thanks for your help
#(Html.Kendo().Grid<dynamic>()
.Name("Grid")
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(true)
.Model(cfg =>
{
cfg.Id("SsdID");
foreach (var property in Model.PropertyDescriptors)
{
cfg.Field(property.Name, property.DataType);
}
})
.Read(cfg => cfg.Type(HttpVerbs.Post)
.Action("ReadDataForDefinition", "ManualDataEntry",
new { id = Model.LDefinitionId }))
.Update(u => u.Type(HttpVerbs.Post).Action("UpdateDataForDefinition","ManualDataEntry",
new { id = Model.LDefinitionId }))
.Create(u => u.Type(HttpVerbs.Post).Action("Create", "ManualDataEntry",
new { id = Model.LDefinitionId }))
)
.Resizable(resizing => resizing.Columns(true))
Columns(columns =>
{
foreach (var property in Model.PropertyDescriptors.Where(desc => desc.DisplayOrder.HasValue))
{
var binding = columns.Bound(property.DataType, property.Name);
if (property.DataType == typeof(DateTime) || property.DataType ==typeof(DateTime?))
binding.Format("{0:d}");
binding.Column.Title = property.Label;
}
columns.Command(command =>
{
command.Edit();
command.Destroy();
});
})
.ToolBar(toolbar => { toolbar.Create(); })
.Pageable(paging =>
{
paging.ButtonCount(10);
paging.PreviousNext(true);
paging.PageSizes(true);
})
.Editable(edit => edit.Mode(GridEditMode.InLine))
.Sortable()
.Scrollable()
.Filterable()
)
For such scenarios only PopUp edit mode is supported. InLine and InCell editing modes are not supported when the using dynamic data or DataTable because the Grid cannot resolve the types of the columns and therefore cannot create proper editor templates. You could check the type and assign templates manually as a workaround. For example:
.Columns(columns =>
{
foreach (System.Data.DataColumn column in Model.Columns)
{
switch (column.DataType.ToString())
{
case "System.Int16":
case "System.Int32":
case "System.Int64":
columns.Bound(column.ColumnName).EditorTemplateName("Integer");
break;
case "System.Decimal":
case "System.Double":
case "System.Float":
columns.Bound(column.ColumnName).EditorTemplateName("Number");
break;
case "System.String":
columns.Bound(column.ColumnName).EditorTemplateName("String");
break;
default:
//etc etc
break;
}
}
})
I am working on asp.net mvc. I am trying to display list of messages in a Kendo mvc ui grid.
I have written the code like,
Html.Kendo().Grid((List<messages>)ViewBag.Messages))
.Name("grdIndox")
.Sortable(m => m.Enabled(true).SortMode(GridSortMode.MultipleColumn))
.HtmlAttributes(new { style = "" })
.Columns(
col =>
{
col.Bound(o => o.RecNo).HtmlAttributes(new { style = "display:none" }).Title("").HeaderHtmlAttributes(new { style = "display:none" });
col.Bound(o => o.NoteDate).Title("Date").Format("{0:MMM d, yyyy}");
col.Bound(o => o.PatName).Title("Patient");
col.Bound(o => o.NoteType).Title("Type");
col.Bound(o => o.Subject);
}
)
.Pageable()
.Selectable(sel => sel.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
.DataSource(
ds => ds.Ajax().ServerOperation(false).Model(m => m.Id(modelid => modelid.RecNo))
.PageSize(10)
//.Read(read => read.Action("Messages_Read", "Msg"))
)
.Events(ev => ev.Change("onSelectingGirdRow"))
)
and i have the field in the table like IsRead-boolean type. so if the message is unread message then i need to format that record with bold font. I have used clientTemplates but with that i am able to format only particular cells i want format entire row. Please guide me.
as Sanja suggested you can use the dataBound event but it will be better to cycle through the tr elements (the rows). Also I assume that you will need the related dataItem to check if the property that indicates if the message is read.
e.g.
dataBound: function ()
{
var grid = this;
grid.tbody.find('>tr').each(function(){
var dataItem = grid.dataItem(this);
if(!dataItem.IsMessageRead)
{
$(this).addClass('someBoldClass');
}
})
}
You can use dataBound event to change your rows.
dataBound: function ()
{
$('td').each(function(){
if(some condition...)
{
$(this).addClass('someBoldClass')}
}
})
}
There is another way to do that.It's called RowAction.
.RowAction(row =>
{
if (condition)
{
row.HtmlAttributes["class"] = "someBoldClass";
}
})
Please note that the RowAction is available only for rows that are rendered on server side. So in your case, you can use RowAction as an alternative to DataBound.
I have a custom editor template for a vehicle part that is used in a telerik grid for insertion in mvc3 razor. The editor template includes a datetime field. On insertion of a new vehicle part the datetime field is incorrect and the format is changed.
For example, if I insert "06/10/2011" which is day 6 , month 10 and year 2011 , in the controller, the dateTime field in the model is "10/06/2011" which is day 10 month 6 and year 211. I am using telerik's date picker
Basically the day and month are becoming switched after submitting to the controller
I have other instances in my code where I am passing a datetime field without an issue, so I believe the problem is the fact that I'm using a custom editor template ...
Here is the code for the grid:
#(Html.Telerik().Grid<VehiclePartsViewModel>()
.Name("VehiclePartsViewModel")
.ToolBar(commands =>
{ commands.Insert();
})
.DataKeys(keys => keys.Add(c => c.Id))
.ClientEvents(events => events.OnRowDataBound("onRowDataBound"))
.DataBinding(dataBinding => dataBinding
.Ajax()
.Insert(MVC.Vehicles.CustomCoverage._InsertPart().GetRouteValueDictionary())
.Select(MVC.Vehicles.CustomCoverage._SelectPart().GetRouteValueDictionary())
.Update(MVC.Vehicles.CustomCoverage._SavePart().GetRouteValueDictionary())
.Delete(MVC.Vehicles.CustomCoverage._DeletePart().GetRouteValueDictionary())
)
.Columns(columns =>
{
omitted..
})
.Footer(false)
.Editable(editing => editing.Mode(GridEditMode.PopUp))
The simplified editor template is :
<div>
#Html.LabelFor(v => v.ItemId, new { #class = "uc-caption"})
#Html.EditorFor(v => v.ItemId)
</div><br />
<div>
#Html.LabelFor(v => v.InstallDate, new { #class = "uc-caption"})
#Html.EditorFor(v => v.InstallDate, new { Modifiable = true })
</div>
I am also using an editor template for dateTime, but I do not believe the issue is here:
#(
Html.Telerik().DatePicker()
.Name(ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty))
.HtmlAttributes(new { id = ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty) + "_wrapper" })
.ShowButton(true)
.Value(Model.HasValue ? Model.Value : new DateTime())
.ClientEvents(events => events.OnChange("onChangeDatePicker"))
.InputHtmlAttributes(new { style = "width:100%"})
.Enable(ViewData["Modifiable"] != null ? (bool)ViewData["Modifiable"] : true)
)
Thanks
Ok so I was finally able to resolve this with telerik .. there seems to be a problem with setting globalization to true .. You have to add a line before it .. This is what my _layout.cshtml looks like now ..
#(Html.Telerik().ScriptRegistrar()
.OnDocumentReady(#<text></text>) //Telerik: This is required because there is still no Telerik components on the page and jQuery(document).ready will not be rendered and the globalization will not work
.Globalization(true)
You probably have problems with globalization/localization of your app.
Different cultures are mixed up.
I had the same problem when posting float values, and solved it by adding this method to Global.asax.cs:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en");
}