Telerik Forums
Kendo UI for jQuery Forum
6 answers
1.0K+ views
Hi guys,

I've been trying to write a generic templating framework that wraps up kendo to deliver a standardised view of a component.
So the idea is that in MVC I would just ask for a url like "~/{type}/Grid" or "~/{type}/View" or "~/{type}/Edit". 
For this to be viable I have to be able to prove that this is both maintainable but also "tweakable" in those situations where a type isn't quite the norm for some reason in its rendering requirements.

I get the feeling Kendo is well suited to this but it does require some magic tricks since MVC does not support generic views.
MVC supports generics of course but no way to say something like this in a view to have a multi type view ...

1.@model ComponentViewModel<T>
2.@Html.Kendo().Grid<T>() ...

... So i started looking at ways to effectively "work around that MVC limit".

I came to the conclusion that If I defined a generic controller and did url binding by convention I could get the type of the controller so I would know what that T actually was and create a ComponentViewModel<T>.
Then if ComponentViewModel<T> had a base class that was the non generic version where T was a type property I could then do something like this to generate an editor for an object of type T ...

01.@using System.Text.RegularExpressions
02.@using App.Models
03.@model ComponentViewModel
04.@{
05.    var rootId = Model.TypeName + Model.ObjectId + "_Editor";
06.    var modelName = Model.TypeName + Model.ObjectId + "_EditorModel";
07.    var m = Activator.CreateInstance(Model.Type);
08.    var dependency = "emedia.dependency.get('" + Model.TypeName + "');";
09.}
10. 
11.<div id="@(rootId)" class="component k-content" data-type="@Model.TypeName" data-item-id="@Model.ObjectId">
12.    <h2><span class="k-sprite edit"></span> @Regex.Replace(Model.Type.Name, @"(?<!_)([A-Z])", " $1"): @Model.ObjectId <img src="@Url.Content("~/Content/close.png")" /></h2>
13.    <script>
14.        $(function () {
15.            @if(Model.CustomDependencyExists)
16.            {
17.                @Html.Raw(dependency)
18.            }
19. 
20.            var @modelName = emedia.createModel('@Model.TypeName', '@Model.ObjectId');
21.            var component = $("#@(rootId)");
22. 
23.            kendo.bind(component, @modelName);
24.            $(".details", component).validate();
25.        });
26.    </script>
27.    <form class="details">
28.        <div data-description="non dynamic templated stuff">
29.            <input type="hidden" name="ID" data-rule-required="true" data-bind="value: ID" />
30.        </div>
31.        <ul class="fieldList">
32.            @{ Html.RenderPartial("EditorTemplates/Object", m); }
33.        </ul>
34.        <hr />
35.        <button class="k-button" data-bind="events: { click: save }">Save</button>
36.    </form>
37.</div>

... Notice the call to Html.RenderPartial where an instance of a T is then MVC templated, pretty neat huh, that works a treat!
All good so far.

So then I thought, ok lets take this a step a further and see if we can template grids, taking things slow I figured it best to start with non editable grids.
Following the same convention I did this ...

01.@using System.Text.RegularExpressions
02.@using App.Models
03.@model GridComponentViewModel
04.@{
05.    var gridName = Model.TypeName + "Grid";
06.    var modelName = Model.TypeName + "Model";
07.    var dependency = "emedia.dependency.get('" + Model.TypeName + "');";
08.    var m = Activator.CreateInstance(Model.Type);
09.}
10. 
11.<div class="component k-content" data-type="@Model.TypeName">
12.    <h2><span class="k-sprite folder"></span> @Regex.Replace(Model.TypeName, @"(?<!_)([A-Z])", " $1")s <img src="@Url.Content("~/Content/close.png")" /></h2>
13.    <script>
14.        $(function () {
15.            //TODO: add signalR behaviour to allow grid update notifications from the server
16.            @if(Model.CustomDependencyExists)
17.            {
18.            @Html.Raw(dependency)
19.            }
20. 
21.            @(gridName)Change = function (arg) {
22.                if(typeof emedia.@(Model.TypeName).gridItemClick != 'undefined') {
23.                    var grid = $("#@(gridName)").data("kendoGrid");
24.                    var item = grid.dataItem(grid.select());
25.                    emedia.@(Model.TypeName).gridItemClick(item);
26.                }
27.            };
28. 
29.            var @modelName = emedia.createModel('@Model.TypeName');
30. 
31.            $("#@(gridName)").kendoGrid({
32.                dataSource: @modelName,
33.                rowTemplate: kendo.Template.compile($("#@(Model.TypeName)Row").html()),
34.                selectable: "row",
35.                columns: emedia.type.columnsFor("@Model.TypeName"),
36.                change: @(gridName)Change,
37.                error: page.error
38.            });
39.        });
40.    </script>
41.    <script id="@(Model.TypeName)Row" type="text/x-kendo-template">
42.        @{ Html.RenderPartial("DisplayTemplates/Row", m); }
43.    </script>
44.    <div id="@(gridName)" class="details"></div>
45.</div>

The row template in this case does the same as the object MVC template (iterates over each property and calls html.displayFor(property)) with the key difference being that the output is wrapped in a td tag to fit in a table row.
Here's where my problems begin.
In the editor template above the MVC view emits a kendo template that looks something like this ...

01.<script id="BusinessTaskRow" type="text/x-kendo-template">
02.    <tr>
03.        <td><span data-bind="text: ID"></span></td>
04.        <td><a href="" data-ref-type="Workflow" data-bind="attr: { data-ref: WorkflowID }, events: { click: refClick }">View Workflow</a></td>
05.        <td><span data-bind="text: Title"></span></td>
06.        <td><pre data-bind="text: Description"></pre></td>
07.        <td><span data-format="dd MMM yyyy" data-bind="text: Created"></span></td>
08.        <td><span data-format="dd MMM yyyy" data-bind="text: Due"></span></td>
09.        <td><span data-bind="text: BusinessTaskStatusID"></span></td></td>
10.    </tr>
11.</script>

.. when the call to kendoGrid is run I get a row for each item in my datasource but I get the template and no bound values in it.
As in, the template is literally the output for each item in the datasource.

So my question ...
Why does initialising a kendo grid only template and not bind (do I have to template something specific) as opposed to the editor scenario which is just binding and not templating?
The editor is working as I would expect, I call bind and it binds, and the markup that is emitted is the expected output on the server.
With the grid implementation however the markup that is emitted is a row definition and to each row I need to bind an item in the datasource.

The demos / documentation aren't clear about how the javascript kendo functions work internally but I would expect for consistency a templating operation to also perform a bind. 
This appears however to not be the case ... or did I miss something?

In other words ...
In an element I want to bind to I might write:
<td><span data-format="dd MMM yyyy" data-bind="text: Created"></span></td>

... but in an element template I would have to write ...
<td><span>#= kendo.toString(Created, 'dd MM yyyy') #</span></td>

My biggest issue is the inconsistency here.
On the server I have an MVC view for outputting an editable version and another for a non editable version, by this convention I now need 2 more versions of each view to account for when the field is being templated vs when it's being bound.

This also raises another interesting question, if a templates data source is updated is this reflected in the templated output since there is no "binding syntax" to inform kendo that the field is bound or do all templated updates trigger a fresh render of the template?

so if I do this ...
<td><span data-format="dd MMM yyyy" data-bind="text: Created, events: { click: myClick }">#= kendo.toString(Created, 'dd MM yyyy') #</span></td>

I can't seem to hook up the click handler.

T. Tsonev
Telerik team
 answered on 03 Dec 2014
2 answers
123 views
Hello,

Have problems with end date of last task. Dates are (end: "2014-11-24T18:00:00", start: "2014-10-13T07:00:00").
Gantt char suppose to hilight my task up to and including 24 day. But chart hilight only till 23 day. It doesnt display one hole work day.

Thank you.
Bozhidar
Telerik team
 answered on 03 Dec 2014
1 answer
87 views
Hello,

I have requirement to allow user that he can add an event on some specific days of calendar. Ex. I am only available on every Monday and Tuesday for whole month. So, user who wants my appointment, can schedule meeting only those 2 days only. all other days will of the calendar will be shown as a grayed. no event can be fired with those days. Is this possible?

I want to show their color with gray background. so, user can easily identify these cells are not  available for scheduling meeting.

Please reply ASAP.
Vladimir Iliev
Telerik team
 answered on 03 Dec 2014
1 answer
187 views
Hi,

is there any way to get hold of the target html element in a event handler?

say e.g. in a ListView.dataBound event, how do I get hold of the ListView html element that is displaying the data?

Thanks,
Stevo
Stevo
Top achievements
Rank 1
 answered on 03 Dec 2014
1 answer
849 views
I'm trying to send filtering data of grid to controller to export data to excel.But I already have the data and I don't need to do a request to get it on client side, I'm filling the grid as the following code:

var dataSource = new kendo.data.DataSource({
data: result.Data,
pageSize: 25
});

$("#grid").kendoGrid({
autoBind: false,
columns: result.Columns,
dataSource: dataSource,
sortable: true,
filterable: true,
resizable: true
});
When I try to get the parameters, i can't because it doesn't exists

var grid = $("#grid").data('kendoGrid');

var parameters = grid.dataSource.transport.parameterMap({
filter: grid.dataSource.filter(),
page: grid.dataSource.page(),
pageSize: grid.dataSource.pageSize(),
sort: grid.dataSource.sort(),
group: grid.dataSource.group()
})

I get an error: Uncaught TypeError: undefined is not a function

If I try to serialize parametersMap without the function grid.dataSource.transport.parameterMap, its serialization occur in a wrong form and the MVC controller parameter can't get the filter value.But if I set a read URL on transport property of dataSource it works perfectly.

So, does anyone knows how to obtain parameterMap without have a read function on transport property ?
Regards!
Rosen
Telerik team
 answered on 03 Dec 2014
4 answers
308 views
Hi,

I'm trying to enable batch editing for a grid bound to an odata data source but having trouble using ParameterMap function to properly format a request.

I started from this example (https://github.com/telerik/kendo-examples-asp-net/tree/master/grid-odata-crud) and my code looks like this:
<html>
    <head>
        <meta charset="utf-8" />
        <title>OData CRUD</title>
        <link href="http://cdn.kendostatic.com/2012.1.322/styles/kendo.common.min.css" rel="stylesheet" />
        <link href="http://cdn.kendostatic.com/2012.1.322/styles/kendo.default.min.css" rel="stylesheet" />
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
        <script src="http://cdn.kendostatic.com/2012.1.322/js/kendo.all.min.js"></script>
    </head>
    <body>
        <div id="grid"></div>
        <script>
            $(document).ready(function () {
                var crudServiceBaseUrl = "/Northwind.svc/Products",
                    dataSource = new kendo.data.DataSource({
                        type: "odata",
                        transport: {
                            read: {
                                url: crudServiceBaseUrl,
                                dataType: "json"
                            },
                            update: {
                                url: function(data) {
                                    return crudServiceBaseUrl + "(" + data.ProductID + ")";
                                }
                            },
                            create: {
                                url: crudServiceBaseUrl
                            },
                            destroy: {
                                url: function(data) {
                                    return crudServiceBaseUrl + "(" + data.ProductID + ")";
                                }
                            },
                            parameterMap: function (data, operation) {
                                if (operation !== "read" && data.models) {
                                    //return { items: kendo.stringify(data.models) };
                                    return { data: kendo.stringify(data.models) };
                                }
                            }
                        },
                        batch: true,
                        pageSize: 10,
                        serverPaging: true,
                        schema: {
                            data: "d",
                            model: {
                                id: "ProductID",
                                fields: {
                                    ProductID: { editable: false, nullable: true },
                                    ProductName: { validation: { required: true } },
                                    UnitPrice: { type: "number", validation: { required: true, min: 1} },
                                    Discontinued: { type: "boolean" },
                                    UnitsInStock: { type: "number", validation: { min: 0, required: true } }
                                }
                            }
                        }
                    });
 
                    $("#grid").kendoGrid({
                        dataSource: dataSource,
                        height: 400,
                        pageable: true,
                        editable: true,
                        toolbar: ["create", "save", "cancel"],
                        columns: [                          
                            "ProductName",
                            { field: "UnitPrice", format: "{0:c}", width: "150px" },
                            { field: "UnitsInStock", width: "150px" },
                            { field: "Discontinued", width: "100px" },
                            { command: ["destroy"], title: " ", width: "110px" }]
                    });
            });
        </script>
    </body>
</html>


I've attached a demo project that includes my web service.

Thanks,
Griffin
Nikolay Rusev
Telerik team
 answered on 03 Dec 2014
7 answers
190 views
Since the Q3 release our code for navigation has become less than reliable.

We used to use app.pane.history to figure out the context of where we are in the application and navigate based on this information. It seems that now app.pane.history only contains one entry of the initial view.

Is there an alternate way for us to figure out where we are in the navigation and use that for our needs?

Thanks,
  Ron.
Petyo
Telerik team
 answered on 03 Dec 2014
1 answer
118 views
The kendo grid has a editable checkbox column, but once click the checkbox, the column headers are not aligned any more, it went back the status where the horizontal scroll bar  was at the beginning, not the current status.  Here a screenshot to show the problem I have, this occurs when I check/uncheck a checkbox in a column.
Alexander Popov
Telerik team
 answered on 03 Dec 2014
2 answers
326 views
How do I set the page size on the listview for MVVM?  the source for the listview and pager is just an array on the model.
Muhammad
Top achievements
Rank 1
 answered on 03 Dec 2014
2 answers
134 views
I'm successfully using the Upload widget to push files on a an Azure storage.
Accept only Excel file of a decent size, so sometimes, the controller on the server side will send an error message in the request response.
Now I can catch this with the 'error' event on client and would like to change the title attribute of the warning icon to show the error message.
How should I do that ?

BTW, using ASP.NET MVC 4, multiselect enabled & asynchonous upload.

Any hint wellcomed.
Christophe
Top achievements
Rank 1
 answered on 03 Dec 2014
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
Application
Drag and Drop
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
Marco
Top achievements
Rank 4
Iron
Iron
Iron
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
Want to show your ninja superpower to fellow developers?
Top users last month
Marco
Top achievements
Rank 4
Iron
Iron
Iron
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
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?