Telerik Forums
Kendo UI for jQuery Forum
2 answers
431 views
I have spent the last week or so using kendo with a MVC3 project. While learning Kendo I have also been playing around with T4 templating.

I have written a template that uses the default List template but I have modified it to use the KendoUI grid.

I thought I would share it with others as hopefully it will some someone else time. It could do with a few tweaks so I might add it to github soon.

<#@ template language="C#" HostSpecific="True" #>
<#@ output extension=".cshtml" #>
<#@ assembly name="System.ComponentModel.DataAnnotations" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data.Entity" #>
<#@ assembly name="System.Data.Linq" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.ComponentModel.DataAnnotations" #>
<#@ import namespace="System.Data.Linq.Mapping" #>
<#@ import namespace="System.Data.Objects.DataClasses" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="Microsoft.VisualStudio.Web.Mvc.Scaffolding.BuiltIn" #>
<#
MvcTextTemplateHost mvcHost = MvcTemplateHost;
#>
@model IEnumerable<#= "<" + mvcHost.ViewDataTypeName + ">" #>
<#
// The following chained if-statement outputs the file header code and markup for a partial view, a content page, or a regular view.
if(mvcHost.IsPartialView) {
#>
 
<#
} else if(mvcHost.IsContentPage) {
#>
 
@{
    ViewBag.Title = "<#= mvcHost.ViewName#>";
<#
if (!String.IsNullOrEmpty(mvcHost.MasterPageFile)) {
#>
    Layout = "<#= mvcHost.MasterPageFile#>";
<#
}
#>
}
 
<h2><#= mvcHost.ViewName#></h2>
 
<#
} else {
#>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <title><#= mvcHost.ViewName #></title>
</head>
<body>
<#
    PushIndent("    ");
}
#>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table id="MYGRID">
<thead>
    <tr>
<#
List<ModelProperty> properties = GetModelProperties(mvcHost.ViewDataType);
foreach (ModelProperty property in properties) {
    if (!property.IsPrimaryKey && property.Scaffold) {
#>
        <th data-field="<#= property.AssociationName #>">
            <#= property.AssociationName #>
        </th>
<#
    }
}
#>
        <th></th>
    </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
    <tr>
<#
foreach (ModelProperty property in properties) {
    if (!property.IsPrimaryKey && property.Scaffold) {
#>
        <td>
            @Html.DisplayFor(modelItem => <#= property.ItemValueExpression #>)
        </td>
<#
    }
}
 
string pkName = GetPrimaryKeyName(mvcHost.ViewDataType);
if (pkName != null) {
#>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.<#= pkName #> }) |
            @Html.ActionLink("Details", "Details", new { id=item.<#= pkName #> }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.<#= pkName #> })
        </td>
<#
} else {
#>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
<#
}
#>
    </tr>
}
</tbody>
</table>
<script>
   $(document).ready(function () {
        setTimeout(function () {
         $("#MYGRID").kendoGrid({
                        dataSource: {
                            type: "json",
                            transport: {
                                read: "/GetJsonData"
                            },
                            schema: {
                                model: {
                                    fields: {
                                    item1:{type:"string"},
                                    item2:{type:"string"},
                                    item3:{type:"string"}
                                    }
                                }
                            },
                            pageSize: 10
                        },
                        columns: [{
                                field:"Id",
                                filterable: false
                            },
                            "Column2",
                            "Column3"
                        ]
                    });
        });
    });
</script>
<#
// The following code closes the asp:Content tag used in the case of a master page and the body and html tags in the case of a regular view page
#>
<#
if(mvcHost.IsContentPage) {
#>
<#
} else if(!mvcHost.IsPartialView && !mvcHost.IsContentPage) {
    ClearIndent();
#>
 
 
</body>
</html>
 
<#
}
#>
<#+
// Describes the information about a property on the model
class ModelProperty {
    public string Name { get; set; }
    public string AssociationName { get; set; }
    public string ValueExpression { get; set; }
    public string ModelValueExpression { get; set; }
    public string ItemValueExpression { get; set; }
    public Type UnderlyingType { get; set; }
    public bool IsPrimaryKey { get; set; }
    public bool IsForeignKey { get; set; }
    public bool IsReadOnly { get; set; }
    public bool Scaffold { get; set; }
}
 
// Change this list to include any non-primitive types you think should be eligible for display/edit
static Type[] bindableNonPrimitiveTypes = new[] {
    typeof(string),
    typeof(decimal),
    typeof(Guid),
    typeof(DateTime),
    typeof(DateTimeOffset),
    typeof(TimeSpan),
};
 
// Call this to get the list of properties in the model. Change this to modify or add your
// own default formatting for display values.
List<ModelProperty> GetModelProperties(Type type) {
    List<ModelProperty> results = GetEligibleProperties(type);
     
    foreach (ModelProperty prop in results) {
        if (prop.UnderlyingType == typeof(double) || prop.UnderlyingType == typeof(decimal)) {
            prop.ModelValueExpression = "String.Format(\"{0:F}\", " + prop.ModelValueExpression + ")";
        }
        else if (prop.UnderlyingType == typeof(DateTime)) {
            prop.ModelValueExpression = "String.Format(\"{0:g}\", " + prop.ModelValueExpression + ")";
        }
    }
 
    return results;
}
 
// Call this to determine if property has scaffolding enabled
bool Scaffold(PropertyInfo property) {
    foreach (object attribute in property.GetCustomAttributes(true)) {
        var scaffoldColumn = attribute as ScaffoldColumnAttribute;
        if (scaffoldColumn != null && !scaffoldColumn.Scaffold) {
            return false;
        }
    }
    return true;
}
 
// Call this to determine if the property represents a primary key. Change the
// code to change the definition of primary key.
bool IsPrimaryKey(PropertyInfo property) {
    if (string.Equals(property.Name, "id", StringComparison.OrdinalIgnoreCase)) {  // EF Code First convention
        return true;
    }
 
    if (string.Equals(property.Name, property.DeclaringType.Name + "id", StringComparison.OrdinalIgnoreCase)) {  // EF Code First convention
        return true;
    }
 
    foreach (object attribute in property.GetCustomAttributes(true)) {
        if (attribute is KeyAttribute) {  // WCF RIA Services and EF Code First explicit
            return true;
        }
         
        var edmScalar = attribute as EdmScalarPropertyAttribute;
        if (edmScalar != null && edmScalar.EntityKeyProperty) {  // EF traditional
            return true;
        }
 
        var column = attribute as ColumnAttribute;
        if (column != null && column.IsPrimaryKey) {  // LINQ to SQL
            return true;
        }
    }
     
    return false;
}
 
// This will return the primary key property name, if and only if there is exactly
// one primary key. Returns null if there is no PK, or the PK is composite.
string GetPrimaryKeyName(Type type) {
    IEnumerable<string> pkNames = GetPrimaryKeyNames(type);
    return pkNames.Count() == 1 ? pkNames.First() : null;
}
 
// This will return all the primary key names. Will return an empty list if there are none.
IEnumerable<string> GetPrimaryKeyNames(Type type) {
    return GetEligibleProperties(type).Where(mp => mp.IsPrimaryKey).Select(mp => mp.Name);
}
 
// Call this to determine if the property represents a foreign key.
bool IsForeignKey(PropertyInfo property) {
    return MvcTemplateHost.RelatedProperties.ContainsKey(property.Name);
}
 
// A foreign key, e.g. CategoryID, will have a value expression of Category.CategoryID
string GetValueExpressionSuffix(PropertyInfo property) {
    RelatedModel propertyModel;
    MvcTemplateHost.RelatedProperties.TryGetValue(property.Name, out propertyModel);
 
    return propertyModel != null ? propertyModel.PropertyName + "." + propertyModel.DisplayPropertyName : property.Name;
}
 
// A foreign key, e.g. CategoryID, will have an association name of Category
string GetAssociationName(PropertyInfo property) {
    RelatedModel propertyModel;
    MvcTemplateHost.RelatedProperties.TryGetValue(property.Name, out propertyModel);
 
    return propertyModel != null ? propertyModel.PropertyName : property.Name;
}
 
// Helper
List<ModelProperty> GetEligibleProperties(Type type) {
    List<ModelProperty> results = new List<ModelProperty>();
 
    foreach (PropertyInfo prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
        Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
        if (prop.GetGetMethod() != null && prop.GetIndexParameters().Length == 0 && IsBindableType(underlyingType)) {
            string valueExpression = GetValueExpressionSuffix(prop);
 
            results.Add(new ModelProperty {
                Name = prop.Name,
                AssociationName = GetAssociationName(prop),
                ValueExpression = valueExpression,
                ModelValueExpression = "Model." + valueExpression,
                ItemValueExpression = "item." + valueExpression,
                UnderlyingType = underlyingType,
                IsPrimaryKey = IsPrimaryKey(prop),
                IsForeignKey = IsForeignKey(prop),
                IsReadOnly = prop.GetSetMethod() == null,
                Scaffold = Scaffold(prop)
            });
        }
    }
 
    return results;
}
 
// Helper
bool IsBindableType(Type type) {
    return type.IsPrimitive || bindableNonPrimitiveTypes.Contains(type);
}
 
MvcTextTemplateHost MvcTemplateHost {
    get {
        return (MvcTextTemplateHost)Host;
    }
}
#>
Sagar
Top achievements
Rank 1
 answered on 29 Nov 2012
1 answer
4.1K+ views
I have the following jsFiddle and want to clear the autocomplete field when the user has selected an item. The following code does not do this:-

$("#input").data("kendoAutoComplete").value("");
 

Is this possible?

//create AutoComplete UI component
$("#input").kendoAutoComplete({
    dataSource: data,
    filter: "startswith",
    placeholder: "Select country...",
    select: function(e) {
        var dataItem = this.dataItem(e.item.index());
        $('#list').append("<li>" + dataItem + "</li>");
        $("#input").data("kendoAutoComplete").value(""); 
    }
});

Georgi Krustev
Telerik team
 answered on 29 Nov 2012
1 answer
112 views
Seems that if you use the mouse to click directly on the splitter without dragging the screen freezes with a modal overlay.

In the prior versions (last 2) there was no overlay used when sliding the splitter.  In this new version when using the mouse to slide the splitter (which doens't appear in the demos), the screen goes gray and when the drag is complete it returns to normal.  However a simple click will freeze the screen.

If someone has seen this issue or knows a work around, I'd really appreciate it.

If I use the keyboard to navigate and resize the splitter the modal overlay is not present.  This only happens on a mouse click.
Alex Gyoshev
Telerik team
 answered on 29 Nov 2012
1 answer
156 views
Is there a way to specify a template for the dataImageUrlField?  For instance, the webservice that generates my DTO is not application specific, so it may generate an object with just "IMAGE_UID_SPECIFIER" in the dataImageUrlField.  Once an app is deployed however, I may want to map this to http://tempuri.com/imagewebservice/IMAGE_UID_SPECIFIER.  In this case I'd want my template to be something like 

dataImageUrlField: http://mytemplateurl/imagewebservice/IMAGE_UID_SPECIFIER

{
  "name": "object1",
  "image": "IMAGE_UID_SPECIFIER"
}


$("#tree").kendoTreeView({
    checkboxes: {
        checkChildren: true
    },
    dataImageUrlField: 'image',
    dataTextField: "name",
});

Any suggestions?

Thanks,

Paul

Alex Gyoshev
Telerik team
 answered on 29 Nov 2012
9 answers
157 views
My grid looks like this:

@(Html.Kendo().Grid<Biblioteka.ViewModels.BookViewModel>()
    .Name("BooksKendoGrid")
    .Columns(columns =>
    {
        columns.Bound(p => p.Title);
        columns.Bound(p => p.Author);
        columns.Bound(p => p.GenreName);
        columns.Bound(p => p.ReleaseDate).Format("{0:d}");
        columns.Bound(p => p.ISBN);
        columns.Bound(p => p.BorrowCount);
        columns.Bound(p => p.RealBookCount);
        columns.Bound(p => p.AddDate).Format("{0:d}");
        columns.Bound(p => p.ModifiedDate).Format("{0:d}");
        columns.Bound(p => p.BookId).Width(150).ClientTemplate("<input type=\"button\" value=\"Edit #= Title #\" style=\"width : 100px;\" onclick=\"openEditWindow(#= BookId #)\"/>"); 
    })   
    .Pageable()
    .Sortable()
    .Scrollable()
    .Filterable()
    .HtmlAttributes(new { style = "height: 200px" })
    .DataSource(dataSource => dataSource
         
                .Ajax()
                .PageSize(2)
                .Model(model =>
                {
                    //The unique identifier (primary key) of the model is the ProductID property
                    model.Id(p => p.BookId);
                })
                       .Read(read => read.Action("BooksKendoGridRead", "Raports")
                  
     )

 
        )
    )

As you can see I had enabled Pageable and I set .PageSize to 2 but it doesn't work it cut other elements in grid ... and leave only 2 
Karol
Top achievements
Rank 1
 answered on 29 Nov 2012
2 answers
116 views
When I use "onclick" then first time it will not fire, the second time it fires but then my other links stop working,

I use PhoneGap/Cordova on Android

Any suggestions? Here is my code:
<!DOCTYPE html>
<html>
<head>
    <title>TEST</title>
 
    <script src="cordova-2.2.0.js"></script>
 
    <script src="js/jquery.min.js"></script>
    <script src="js/kendo.mobile.min.js"></script>
 
    <link href="css/kendo.common.min.css" rel="stylesheet" />
    <link href="css/kendo.mobile.all.min.css" rel="stylesheet" />
</head>
 
<body>
     
    <div id="div1" data-role="view" data-title="Hello World">
     
    <h2>Hello App</h2>
 
    <ul data-role="listview" data-style="inset" data-type="group">
        <li>Please select:
            <ul>
                <li data-icon="play"><a href="Page1.html">Page 1</a></li>
             
                <li data-icon="play"><a href="#" onclick="test1();">Test</a></li>
            </ul>
        </li>
    </ul>
</div>
 
 
 
    <script>
        window.kendoMobileApplication = new kendo.mobile.Application(document.body);
         
        function test1()
        {
            alert('hello there...');
        }
         
    </script>
     
 
</body>
</html>
Petyo
Telerik team
 answered on 29 Nov 2012
1 answer
258 views
Hi,

          My simple apps needs to point a website for example (www.mywebsite.com).  And when it display the page, it should show the whole page and the user can zoom in or out. 
         
           Please let me know on how to do it or whatever KendoUI can do about it.

Thanks
Petyo
Telerik team
 answered on 29 Nov 2012
1 answer
303 views
I am using MVC.
I am having some difficulty in creating a filter for a column 'Name' where startswith 0-9

grid.dataSource.filter([
    { field: "Name", operator: "startswith", value: "0" },
    { field: "Name", operator: "startswith", value: "2" },
    { field: "Name", operator: "startswith", value: "3" },
    { field: "Name", operator: "startswith", value: "4" },
    { field: "Name", operator: "startswith", value: "5" }
]);
Above is abbrieviated....
Basically i have a text field 'Name' and i need to show any record that starts with 0-9.

Seems like no matter which way i phrase the filter, the filter on the DataSourceRequest never haves more that two filters (CompositeFilter).

Any help would be great. thanks.  Logically i know i could have ten colums and filter by all ten columns for some value so my feeling is internally it is grouping by "Name" b/c the demos only support two filters per column.

-Trent
Atanas Korchev
Telerik team
 answered on 29 Nov 2012
1 answer
109 views
I have the following template: 
        <script type="text/x-kendo-template" id="recentPostListViewTemplate">
            <div id="#= id #" data-role="touch" data-tap="myTouch.tap">#= title #</div>
            <div class="articleBody" id="body-#= id #">
            #= content #<br>
            <a href=#= custom_fields.syndication_permalink[0] #>Read Full Story</a>
            </div>
        </script>
It works great at first. Once I add to the list view using endless scroll the newly generated items aren't tappable. This is my myTouch section:
window.myTouch = {
    tap : function(e) {
        var id = e.touch['target']['context']['id'];
        console.log(id);
        $('#body-' + id).toggle();
    }
}
Is there something I have to do to get this to work on the newly generated list view items? I tried the old stand by of an onClick event but just doesn't work right on the iPhone.

Thanks.
Petyo
Telerik team
 answered on 29 Nov 2012
1 answer
94 views
Hi,

Is it possible to have Kendo UI widgets + DataViz widgets on the same page?
I wanted to have Grid(Popup Editing, Inline Editing etc.), Slider, AutoComplete, Rich Text Field and a Scatter Chart on the same page.
I have downloaded the latest trial package - kendoui.trial.2012.3.1114

I have added the files as below..

    <link href="../../content/shared/styles/examples-offline.css" rel="stylesheet">
    <link href="../../../styles/kendo.common.min.css" rel="stylesheet">
    <link href="../../../styles/kendo.default.min.css" rel="stylesheet">

    <script src="../../../js/jquery.min.js"></script>
    <script src="../../../js/kendo.web.min.js"></script>
    <script src="../../content/shared/js/console.js"></script>
    <script src="../../../js/kendo.dataviz.min.js"></script>

But on adding "kendo.dataviz.min.js", other widgets seems to misbehave.
How to overcome this and have both UI widgets and DataViz widgets on the same page..???


Thanks,
Vishnu
Atanas Korchev
Telerik team
 answered on 29 Nov 2012
Narrow your results
Selected tags
Tags
Grid
General Discussions
Charts
Data Source
Scheduler
DropDownList
TreeView
MVVM
Editor
Window
DatePicker
Spreadsheet
Upload
ListView (Mobile)
ComboBox
TabStrip
MultiSelect
AutoComplete
ListView
Menu
Templates
Gantt
Validation
TreeList
Diagram
NumericTextBox
Splitter
PanelBar
Drag and Drop
Application
Map
ToolTip
Calendar
PivotGrid
ScrollView (Mobile)
Toolbar
TabStrip (Mobile)
Slider
Button (Mobile)
Filter
SPA
Drawing API
Drawer (Mobile)
Globalization
LinearGauge
Sortable
ModalView
Hierarchical Data Source
Button
FileManager
MaskedTextBox
View
Form
NavBar
Notification
Switch (Mobile)
SplitView
ListBox
DropDownTree
PDFViewer
Sparkline
ActionSheet
TileLayout
PopOver (Mobile)
TreeMap
ButtonGroup
ColorPicker
Pager
Styling
Chat
MultiColumnComboBox
Dialog
DateRangePicker
Checkbox
Timeline
Drawer
DateInput
ProgressBar
MediaPlayer
ImageEditor
TextBox
OrgChart
Accessibility
Effects
PivotGridV2
Licensing
ScrollView
Switch
TextArea
BulletChart
QRCode
ResponsivePanel
Wizard
CheckBoxGroup
Localization
Barcode
Breadcrumb
Collapsible
MultiViewCalendar
Touch
RadioButton
Stepper
Card
ExpansionPanel
Rating
RadioGroup
Badge
Captcha
Heatmap
AppBar
Loader
Security
TaskBoard
Popover
DockManager
TimePicker
FloatingActionButton
CircularGauge
ColorGradient
ColorPalette
DropDownButton
TimeDurationPicker
ToggleButton
BottomNavigation
Ripple
SkeletonContainer
Avatar
Circular ProgressBar
FlatColorPicker
SplitButton
Signature
Chip
ChipList
VS Code Extension
AIPrompt
PropertyGrid
Sankey
Chart Wizard
OTP Input
SpeechToTextButton
InlineAIPrompt
StockChart
ContextMenu
DateTimePicker
RadialGauge
ArcGauge
AICodingAssistant
SmartPasteButton
PromptBox
SegmentedControl
+? more
Top users last month
Hiba
Top achievements
Rank 1
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Max
Top achievements
Rank 1
Veteran
Iron
Alina
Top achievements
Rank 1
Rakhee
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Hiba
Top achievements
Rank 1
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Max
Top achievements
Rank 1
Veteran
Iron
Alina
Top achievements
Rank 1
Rakhee
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?