Kendo UI Grid

Video: How to add custom Date filter column in Kendo UI Grid using ASP.NET MVC Wrapper

Recently i wrote a blog post showcasing how to add a custom Date filter column in Kendo UI Grid using our Telerik  UI for ASP.NET MVC wrappers. You can find the blog here. In this blog post i will be providing a screen case i have recorded where i give you step by step instruction on how to create a custom Date filter column. If you have read the blog post – now you get to see it in action. Continue reading

Kendo UI

Resources from Webinar “Kendo UI Wrappers for ASP.NET MVC Core 1.0”

On May 26 2016, we finished yet another webinar. If you are here at our site for the first time, do note that we conduct webinars almost 3 Thursdays in the month , every month @ 12PM IST. If you want to know more about the schedules, you can check out our announcement category and there will be a blog post with the schedule.This week we did one of my favorite topics – ASP.NET MVC Core 1.0 + Kendo UI Wrappers or Tag Helpers. Continue reading

Kendo UI Grid Wrapper for ASP.NET MVC – Getting Started

Overview:

In this blog post I will be exploring how to get started with our Kendo UI Grid Wrapper for ASP.NET MVC. We will take a basic usage of displaying data in a grid format in an ASP.NET MVC view. To know more about Kendo UI Web controls head over to www.kendoui.com. If you want to follow along with this blog post, you can do so by downloading a 30 day free trial of Kendo UI Complete for ASP.NET MVC.

Getting Started:

First lets create a ASP.NET MVC project. I am using Visual Studio 2012. When you install Kendo UI, we also install certain project templates which make it easy to create kendo UI based ASP.NET MVC project. I assuming you have installed Kendo UI Web for the rest of the post. In Visual Studio, select File > New Project > Web > Kendo UI for ASP.NET MVC. Give it a name and wait for Visual Studio to spin up the new project.

Datasource:

For the sake of this blog post, I will be using Northwind database. I will also be using ADO.NET Entity Model to Northwind database and use Customers table data. So go ahead and add a ADO.NET Entity Model to your project. We will use the entity data model to fetch data and bind it to the grid. I have also created a CustomerViewModel so that I can use this as the Model to the view. Here is the code for the CustomerViewModel:


public class CustomerViewModel
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Country { get; set; }
}

Home Controller & Index Action method changes:

We will read the customers data, build CustomerViewModel list and add this to view as a Model. Here is the Index Action method code snippet:


public ActionResult Index()
{
var customerViewModelList = GetCustomers();
return View(customerViewModelList);
}

GetCustomers is a helper method which converts Customers entity to CustomerViewModel entity and return a list. Here is the code snippet of GetCustomers method:


private IEnumerable<CustomerViewModel> GetCustomers()
{
var context = new NORTHWINDEntities();
var customers = context.Customers.Select(customer => new CustomerViewModel
{
CustomerID = customer.CustomerID,
CompanyName = customer.CompanyName,
ContactName = customer.ContactName,
ContactTitle = customer.ContactTitle,
Country = customer.Country,
});
return customers;
}

Adding Grid to View:

In order to use a grid on a view, you will use the GridBuilder. GridBuilder supports the following overloaded methods for creating the grid:


public virtual GridBuilder<T> Grid<T>() where T : class;

public virtual GridBuilder<DataRowView> Grid(DataTable dataSource);

public virtual GridBuilder<DataRowView> Grid(DataView dataSource);

public virtual GridBuilder<T> Grid<T>(IEnumerable<T> dataSource) where T : class;

public virtual GridBuilder<T> Grid<T>(string dataSourceViewDataKey) where T : class;

in this blog post we will be using the method where it allows us to pass a IEnumerable as the data source. First lets take a look at the code snippet. Following the snippet I will explain the code in detail:


@using GridGettingStarted.Models
@model IEnumerable<CustomerViewModel>
@(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.ContactName).Width(140);
columns.Bound(c => c.ContactTitle).Width(190);
columns.Bound(c => c.CompanyName);
columns.Bound(c => c.Country).Width(110);
})
.Pageable()
.Sortable()
.Groupable()
.Filterable()
)

Well that’s all it takes to create a grid in MVC. Now lets go over the code in detail.

  • We pass the Model which is IEnumerable<CustomerViewModel> in this case to the GridBuilder
  • All widgets in Kendo UI needs to be named, so we provide a name using the Name() method
  • We define columns of the grid using the Columns() method. We can provide lambda expression to indicate which columns should be bound
  • In order to allow paging on the grid, we just add the Pageable() method
  • Sorting on the grid is enabled by adding the Sorting() method
  • Grouping is enabled by adding the Groupable() method
  • Similarly, filtering is provided by adding the Filterable() method

Now build the project and run the application. Following is the output of the code we just wrote:

image

Server Operation False:

At this moment if you click on a pager link or try to sort or try to group, Kendo UI Grid will be default send a request back to Server. That’s the default behavior that the grid works with. It assumes that Server would like to perform operation before getting the data. In this scenario that is not intended for me. I have got all the data that I need and I have given it to the grid. So it should do all the operation at client side rather than sending a request to server. For this to happen we just need to let the Grid DataSource not to perform server operation. This can be done by setting the Grid DataSource setting as  below:


@(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.ContactName).Width(140);
columns.Bound(c => c.ContactTitle).Width(190);
columns.Bound(c => c.CompanyName);
columns.Bound(c => c.Country).Width(110);
})
.Pageable()
.Sortable()
.Groupable()
.Filterable()
.DataSource(source => source
.Ajax()
.ServerOperation(false)
)
)

now when you run the project and perform any operations, grid will not send a request to the server but do it client side.

Conclusion:

This blog post was like a primer to anybody who would like to get started with Kendo UI Grid Wrapper for ASP.NET MVC. With just 15 lines of settings you will have a full fledged grid in your app within no time. If you are interested in Kendo UI Grid, do download a 30 day free trial at www.kendoui.com.

image_thumb.png

How to defer Kendo UI Initialization scripts when using Kendo UI ASP.NET MVC Wrappers

About Kendo UI:

Kendo UI is a flagship product from Telerik which is a HTML5 powered client side JavaScript framework. We have Widgets/Controls apart from a plethora of framework level goodies like MVVM, Validation, Globalization etc. out of the box. Although this is a client side framework which means that you program against Kendo UI using JavaScript – obviously. But Kendo UI also has a server side wrapper for ASP.NET MVC very similar to HtmlHelper extensions available from Microsoft (TextBox, CheckBox etc.). What this means is, the wrappers shield you from writing JavaScript yourself and instead you code in your natural comfort zone of C# and Razor and the wrappers output the JavaScript for you. These JavaScript are the initialization scripts for the widgets.

Widget Initialization Scripts:

Kendo UI relies  on 2 things – JQuery framework and Kendo Web JavaScript file. Before you can start working with Kendo you need these 2 JavaScript file references added to your page. Assume that we have referenced the 2 script files in the head section of the page.

When you use wrappers to code on the server side, the wrappers output the necessary JavaScript code required for Kendo UI to work on the client side. Note: the wrappers do not out put the markup rather output the JavaScript which is required to initiate a widget on the client side. But the initialization code blocks are rendered right at the place where the widget was defined in your source code.

To illustrate this – lets take a simplest of the code as an example. We will use the AutoComplete Widget and see the rendered code on the client side. Here is the Razor syntax using AutoComplete Kendo UI Wrapper:

@(Html.Kendo().AutoComplete()
.Name("countries")
.Filter("startswith")
.Placeholder("Select country...")
.BindTo(new string[] {
"Bulgaria",
"India",
"Australia",
"Germany",
"USA",
"UK",
"Hong Kong"
})
.Separator(", ")
)
<div class="hint">Start typing the name of an European country</div>

Notice that we have a div after the autocomplete widget. Now at run time right click on the browser and view the source code. Here is the code that gets generated:


<input id="countries" name="countries" type="text" /><script>

jQuery(function(){jQuery("#countries").kendoAutoComplete({"dataSource":["Bulgaria","India","Australia","Germany","USA","UK"],"filter":"startswith","placeholder":"Select country...","separator":", "});});

</script>

<div class="hint">Start typing the name of an European country</div>

As you can see the initialization script code is rendered right at the place where we had defined the wrapper in our source code. This works fine as long as the Jquery and Kendo script references are done at the head level of the document. In next section we will see what happens when we move the script reference to the end of the page.

Following Best Practice for Script References:

One of the best practice of the web development is to load any scripts we need at the end of the page. What this does is it doesn’t block the page from loading. Page continues to load & render and the scripts gets loaded at the end and user does not see any blockings in the page load. But we have a problem. As seen in the previous section, the widget initialization script gets rendered at the position where the widget was defined in source code and gets executed immediately. if the Jquery and Kendo scripts are loaded at the end of the page, the initialization script will fail with errors as the frameworks are not yet loaded. Here is the error we get:

image

Deferring Initialization Scripts:

Luckily, Kendo UI Wrappers have a answer to the initialization scenario we saw in the previous section. Each of the widget wrappers expose a method called Deferred(). It’s a fluent method and will suppress immediate script statement rendering. The next question we may have is – we deferred the initialization, but how do we initialize the widget once page is loaded. Answer is, Kendo wrappers expose one more fluent method called DeferredScripts(). DeferredScripts method will output all the previously deferred initialization statements.

Here is the updated code to handle deferring the scripts:

First, I moved the Jquery and Kendo script  reference to end of the page and made a call to RenderSection. This is the section where we will out put the initialization scripts from the pages.

<script src="@Url.Content("~/Scripts/kendo/2013.2.716/jquery.min.js")"></script>
<script src="@Url.Content("~/Scripts/kendo/2013.2.716/kendo.all.min.js")"></script>
@RenderSection("PageScripts", required:false)

Second, I have called the Deferred() fluent method on the auto complete wrapper. Declared a section PageScripts and called DeferredScripts() fluent method to output the deferred statements.

@(Html.Kendo().AutoComplete()
.Name("countries")
.Filter("startswith")
.Placeholder("Select country...")
.BindTo(new string[] {
"Bulgaria",
"India",
"Australia",
"Germany",
"USA",
"UK",
"Hong Kong"
})
.Separator(", ")
.Deferred()
)
<div class="hint">Start typing the name of an European country</div>
@section PageScripts {
@Html.Kendo().DeferredScripts()
}

With the above code changes, we now have the initialization statements deferred till we explicitly call the DeferredScripts() fluent method in the PageScripts section. Here is the generated code at run time:

<input id="countries" name="countries" type="text" />
<div class="hint">Start typing the name of an European country</div>
<script src="<a href="http://localhost:39897/Scripts/kendo/2013.2.716/jquery.min.js">/Scripts/kendo/2013.2.716/jquery.min.js</a>"></script>
<script src="<a href="http://localhost:39897/Scripts/kendo/2013.2.716/kendo.all.min.js">/Scripts/kendo/2013.2.716/kendo.all.min.js</a>"></script>
<script>jQuery(function(){jQuery("#countries").kendoAutoComplete({"dataSource":["Bulgaria","India","Australia","Germany","USA","UK","Hong Kong"],"filter":"startswith","placeholder":"Select country...","separator":", "});});</script>

Conclusion:

When using Kendo UI ASP.NET MVC wrappers, you should pay attention to how you want to use the widgets. Since the wrappers output the initialization statements immediately at the position of the wrappers definition, it needs the JQuery and kendo scripts to be available upfront. If you follow the best practice of loading the scripts at the end of the page, you will need to defer the initialization statement and manually output all deferred statements after you have loaded the JQuery and Kendo scripts. This blog post introduces you to Deferred() and DeferredScripts() fluent method supported in Kendo. Hope this information is useful to you. If you have not experienced Kendo UI, encourage you to visit www.kendoui.com and take a look at our demos.

Till next time, Happy Coding!

Kendo UI Logo

Resources for Webinar “Developing ASP.NET MVC Applications Quicker with Kendo UI”

On Jul 11 we conducted a webinar titled “Developing ASP.NET MVC Application Quicker with kendo UI”. This is part of the ongoing webinar series we here at Telerik India are doing targeting the APAC region. We call this the Telerik .NET Ninja Developer Webinar series. You can take a look at the Jun-Jul schedule here: https://telerikhelper.net/2013/05/24/telerik-webcasts-june-july/

image

Kendo UI is a HTML5 based JavaScript framework for developing HTML5 based sites or apps. Its everything you need to develop the sites and apps. Its one package which will give you pretty much everything you need to develop a HTML5 based apps or sites. Although it is a client side framework and that means a lot of JavaScripting, we have you covered if you want to develop on the server side. We have what we call as ASP.NET MVC Wrappers for Kendo UI. This give you the power of JavaScript but the productivity of server side. So this webinar was all about how you can build UI quicker in ASP.NET MVC using Kendo UI.

Slide Deck:

Here is the slide deck which I used for the webinar:

Webinar Video:

For those of you who missed attending the webinar live, we have it covered for you. We record all our webinars and so was this one. Here is the recording of the webinar:

Questions & Answers:

During the webinar, my team tried hard to answer as many questions as we can. With the interest of the time we normally collect all your questions and try to answer them through this recap blog post. So here is all the questions and answers for them:

Q: What is the license cost or purchase cost for Kendo ?
A: kendo UI costing is available at this page: http://www.kendoui.com/purchase.aspx

Q: Can we use Kendo UI for asp .net apps without MVC?
A: Yes you can. But note that Kendo UI is all about client side. So no server side programming of Kendo UI controls. You will need to use JavaScript way of working with Kendo UI in technology other than ASP.NET MVC. The server side wrappers are available only for ASP.NET MVC.

Q: Is Kendo UI available as part of Telerik Controls ?
A: You can buy Kendo UI as a single product. Here is the Kendo UI pricing – http://www.kendoui.com/purchase.aspx.  Also, if you buy any of our DevCraft bundles, kendo UI is included in the bundle. Here is our DevCraft bundle pricing – http://www.telerik.com/purchase.aspx

Q: Any live application developed using kendo UI?
A: You can take a look at www.kendouimusicstore.com. This is a famous reference app for ASP.NET MVC which was developed by Microsoft. We took the same and converted it to a Kendo UI application with front end being completely done using Kendo UI controls and back end powered by Web API.

Q: Before starting development, which language knowledge required?
A: If you know JavaScript, then you know Kendo UI. Kendo UI is built on JQuery. So nothing new to learn. If you want to program Kendo UI using a server side technology – we support Server Side Wrappers for ASP.NET MVC, JSP and PHP.

Q: Can we use kendo UI with Web API?
A: Yes absolutely. Kendo UI has Data Source that easily connects with Web API.

Q: To develop app in Kendo UI little bit JS is enough?
A: Yes, you do require JS knowledge especially awareness of jquery kind of syntax. But you can directly use ASP.NET MVC, PHP or JSP server side technologies too.

Q: How do we decide between jQuery UI and Kendo UI? Do we have comparison charts between these products?
A: Take a look at this article – http://jqueryuivskendoui.com/

Q: Will Kendo UI Support SharePoint 2010?
A: Kendo UI is a client side control set. As long as you develop a webpart which supports accessing external JavaScript and Stylesheet, Kendo UI can be used anywhere.

Q: Can we use knockout.js in Kendo UI or it’s not required because it’s different JavaScript library similar to knockout.js
A: Kendo UI has all the capabilities that you require (even of KO). But you can also use KO with Kendo UI.

Q: What kindsof data sources are supported?
A: Out of the box Kendo UI Data Source can handle JSON and XML.

Q: Does it support multiple cultures?
A: Globalization is one of the features in built in Kendo UI. So you can include the appropriate culture Kendo UI JS file and set the culture you want to work with. Rest will be handled by Kendo UI.

Q: Is Kendo UI a jquery plugin?
A: Kendo UI is not a Jquery plugin or a clone. Kendo UI is written from ground up but is based on Jquery. Jquery is the only dependency Kendo UI has. All the constructs in Kendo UI are similar to Jquery so that the learning curve is less.

Q: What are the key features of Kendo UI Mobile?
A: You can take a look at our Kendo UI Mobile product page – http://www.kendoui.com/mobile.aspx

Q: Is there any Kendo Controls for Winforms?
A: No. Kendo UI is for Desktop Browser based application and Cross Platform Hybrid Mobile Application development. for WinForms we have a separate control suite which you can take a look at here – http://www.telerik.com/products/winforms.aspx

Q: Can we have Scheduler control in Kendo UI?
A: Yes. Scheduler control is available as part of Q2 2013 release of Kendo UI.

Q: Can we use Kendo UI to show data in modal and provide CRUD operations with validations in Kendo UI
A: Kendo UI Grid already supports this feature. Take a look at our Grid demos online at – http://demos.kendoui.com/web/grid/index.html

Q: Kendo UI is only a Java Script library or any server side components are also involved?
A: Kendo UI is a client side HTML5 based JavaScript framework. We have server side wrappers to speed up your Kendo UI programming. The wrappers just output the necessary JavaScript code which otherwise you would have to write.

Q: Can we bind data from SQL DB?
A: You need to create Web Service or Web API which can return the data as JSON. Kendo UI has a JavaScript data source which can work out of the box with a service returning JSON payload or xml payload.

Q: Does that mean apps developed using Kendo UI can be used on mobile browser?
A: Yes. Kendo UI Web controls are touch aware and can run on all modern browsers.

Q: How do we compile to native app after completing the app in Kendo UI mobile?
A: If you are using our Cloud Based IDE – ICENIUM, it lets you build for iOS and Android platform right from the IDE. Otherwise you will need to use PhoneGap build mechanism to generate the package.

Q: How Kendo UI is different when compared with Knockout.Js ?
A: As far as I know, Knockout.js is a library to achieve data binding where as Kendo UI is a complete framework which provide Widgets/MVVM/Validation etc.

Q: Is there any project template for VS2012 from kendo UI?
A: Yes. When you install Kendo UI using our installers, we ship in a Visual Studio project template to speed up your ASP.NET MVC development with Kendo UI.

Q: Can we integrate WPF app in this Kendo UI?
A: WPF is a different technology set. Kendo UI is meant for Web applications & not WPF.

Q: What are the mandatory script files need to be included in kendo UI on working in MVC 4?
A: You need to include Kendo UI Web JavaScript and Kendo Stylesheet files into your project.

Q: Does charts in DataViz support on IE8 ?
A: Yes, it is supported.

Q: Can the CSS be modified as per our need?
A: Yes absolutely. We even provide an online tool to facilitate this: http://demos.kendoui.com/themebuilder/index.html

Q: Can you talk about Kendo UI licensing?
A: Kendo UI is licensed on per developer basis. For more details and discounts, please write to sales@telerikindia.com

Q: Do you have any facility for group license?
A: Yes, absolutely. Please write to sales@telerikindia.com

Q: In the era where the line between PC/Laptop display and mobile display getting blurred day by day, e.g. PCs getting touchscreen, mobiles/tablets getting Full HD/Retina displays, how one should plan their investment for web application? I mean if we are targetting global reach, how you recommend Kendo UI for mobile/MVC?
A: Kendo UI Mobile is used to create Cross-Platform Apps. Using that you create apps for devices and phones . Kendo MVC Wrapper is used in MVC based web apps .

Q: Is this light weight control?
A: Yes, Kendo controls are very light weight controls with no addition to ViewState etc. Since it can use the client side processing capabilities as well, the performance is phenomenonal. It also supports virtualization etc.

Q: Can you elaborate more on “Virtualization”?
A: do take a look here: http://demos.kendoui.com/web/grid/virtualization-remote-data.html

Q: what is MVVM framework?
A: Kendo comes with its own optimized MVVM framework. Please refer to the following webcast that we had done on the same: https://telerikhelper.net/2013/05/31/resources-for-webinar-mvvm-validation-using-kendo-ui-in-web-applications/

Q: Can we use trail version control in any professional web site?
A: No, trial license explicitly forbids you from using it in live/professional web sites. Please write to sales@telerikindia.com and we can help you further with more information.

Q: Not clear how chart series changes according to data
A: Learn more about charts here http://demos.kendoui.com/dataviz/bar-charts/index.html

Q: How can we do conditional validation in KENDO UI?
A: Please do take a look at the demo here: http://demos.kendoui.com/web/validator/index.html

Q: Kendo is for web based or mobile based services?
A: Kendo UI web is meant for web apps. Kendo UI Mobile is meant for mobile. They both share a common base framework.

Q: Will there be wrapper for ASP.NET wrapper in future. We currently use ASP.NET Telerik.
A: We already have a wrapper for ASP.NET MVC. If you are using WebForms, the RadControls are the ideal controls to use. We are constantly adding & updating those controls.

Q: Can we use Kendo UI for java web application
A: Yes, we have a JSP wrapper for the same. More details here: http://www.kendoui.com/server-wrappers/jsp.aspx

Q: Can i use knockout.js with Kendo UI mvc
A: Pls take a look here: http://rniemeyer.github.io/knockout-kendo/

Q: Can we use kendo controls in VS2008
A: Sure, you can. they are simple JS libraries that can be added. It has no IDE requirements.

Q: Is there any other separate editor for Telerik development?
A: We don’t have any IDE requirement for Kendo UI. If you are doing MVC development you will want to use VS and Kendo UI wrapper for MVC

Q: Does the kendo mobile support in all the browser?
A: Yes. It only requires HTML 5 support in the browser. All modern browsers support that.

.NET Ninja T-Shirt Giveaway:

we select 2 person from the webinar attendees and give away our .NET Ninja T-Shirt in each of our webinars. we have picked up 2 lucky persons in this webinar too. They are:

  • Karthikeyan R

  • Harvinder Singh

Congratulations to the winners. We will be contacting you shortly and we will ship your t-shirts. Rest of the folks don’t worry – we still have loads of webinars lined up for this year. So do attend our future webinars without fail and try your luck to be the .NET Ninja.

Till next time – Happy Coding.

image_thumb.png

Kendo ColorPicker Wrapper for ASP.NET MVC

Overview:

This is the eight post in the series on Kendo UI wrappers for ASP.NET MVC. We will look at one more wrapper in this post namely Color Picker. This post is part of a getting started with Kendo UI wrappers for ASP.NET MVC and you can find the index post here.

What is ColorPicker Wrapper?

The ColorPicker is a drop-down widget for selecting colors. It’s designed to replace a HTML5 <input type="color"> field, which is not yet widely supported in browsers. ColorPicker widget provides a user-friendly interface for picking colors.

image

Fig 1: ColorPicker Widget

ColorPicker wrapper is just a kendo helper for ASP.NET MVC.

Basic Usage:

In order to use the ColorPicker widget on any page, we will use the ColorPicker wrapper or helper available as part of the kendo wrappers. Following is the code to create a color picker on any page. Note that Name() is a mandatory setting for the color picker. Without setting the name we will get an exception which will tell that name is not set.

Here is the output of the above code:

image

Fig 2: Color Picker Basic Usage

Color Palette:

We can customize the color palette that is displayed in the color picker drop down. The wrapper provides Palette() configuration method which accepts the palette. There 2 ways of providing the palette. They are:

1. ColorPickerPalette Enumeration:

We can pass enum called ColorPickerPalette to Palette() method of the widget. The enum supports Basic, None and WebSafe palette. Here is the code for setting the palette:

Here is the output of setting palette to Basic, WebSafe and None:

image

Fig 3: Basic Color Palette

image

Fig 4: Web Safe Palette

image

Fig 5: No Palette

2. Provide Palette as Array

We can pass a string array to Palette() method which should contain the hex codes of the colors we want to show in the palette. Here is the code to do this:

And here is the output of the code changes:

image

Fig 6: Custom Palette

Custom Color Tile Size:

So far we have seen how the color picker works and what palettes it supports. One thing to notice in palettes is the size of the individual color tiles. It looks small. What if we wanted a bigger tile? The wrapper supports a TileSize() configuration method which takes in an integer. Here is a code set the tile sizes of the color palette:

Here is the output of above code changes:

image

Fig 7: Custom Color Tile Size

Accessing control on client:

So far we have seen how to instantiate a control with the helpers. And since the Kendo controls are all client side, lets take a look at how to get the control using JavaScript code. Kendo controls are HTML5 compliant so we make use of HTML5 attributes like “data-“ and construct our controls. You can use the jquery data() method to get to an already instantiated control. Here is the code snippet for the same:

Accessing & Setting Value from client side:

All kendo controls have rich client side API support. One of the api method is value() which lets you read the selected value and also set new value of the color picker. Here is the code:

In the above code – we just created the color picker using the server side helpers. On client side, after document has loaded, we grab the control, use the value() method to set a new value. And then use the same method to read back the selected value.

Handling Events:

Color Picker supports four events which can be handled on the client side. They are:

  • change: Fires when a color was selected
  • select: Fires when a new color is displayed in the drop-down picker
  • open: Fires when the picker popup is opening
  • close: Fire when the picker popup is closing

Here is the code wire up the events and JavaScript code for the handlers:

Summary:

Through this post we looked at yet another kendo wrapper for MVC namely Color Picker. Using color picker is as easy as settings some configuration methods and the rest is done by the helper for you. Hope this excites you to test out Kendo UI in your projects.

Till next time, Happy Coding.

Kendo Editor

Kendo Editor Wrapper for ASP.NET MVC

Overview:

This is the seventh post in the series on Kendo UI wrappers for ASP.NET MVC. We will look at one more wrapper in this post namely Editor. This post is part of a getting started with Kendo UI wrappers for ASP.NET MVC and you can find the index post here.

What is Editor Wrapper?

First lets understand what is a Editor control all about. The Editor allows users to create rich text content by means of a WYSIWYG interface. The generated widget value is comprise of XHTML markup.

imageFig 1: Kendo Editor

The Editor Wrapper for ASP.NET MVC is a server side wrapper for Kendo UI Editor which is a JavaScript based widget.

Basic Usage:

In order to use the kendo editor on any web page, we will use the Editor wrapper available as part part of the Kendo Wrappers for ASP.NET MVC. Following is the code for the basic usage where in we just instantiate the kendo editor and give it a name while setting the width & height.

Note that you need to set the Name for the editor. Other wise we will be issued a InvalidOperation exception at runtime which will say “Name cannot be blank”. Following is the screen shot of the output:

image

Fig 2: Kendo Editor Basic Usage

Tools Bar:

The top bar on the editor is known as Tools bar. By default the editor will display the basic necessary tools without we explicitly specifying them. The editor supports the following tool options:

1. Bold 13. InsertUnorderedList
2. Italic 14. InsertOrderedList
3. Underline 15. Indent
4. Strikethrough 16. Outdent
5. FontName 17. FormatBlock
6. FontSize 18. CreateLink
7. FontColor 19. Unlink
8. BackColor 20. InsertImage
9. JustifyLeft 21. SubScript
10. JustifyCenter 22. SuperScript
11. JustifyRight
12. JustifyFull

Table 1: Tool Bar Configuration Option

So here is the code to get all the tools on the tool bar:

Here is the output of the above code changes:

image

Fig 3: All Tools on the Tool Bar

Note: In order to get all the tools we just added Subscript() and Superscript() options. That is because, editor control will default add tools from 1 to 20 in the above table. So we just added missing tools. If you want to keep only some tools on the tool bar, you will need to first clear the tools and then add the tool option you want. Following code will add only FontName, FontSize, ForeColor and BackColor to the tool bar:

Here is the output of the above code changes:

image

Fig 4: Custom Options in Tool Bar

Custom Tool Bar Options:

So far we saw the default tool bar options available in Kendo. What if we want to have a custom tool bar option. Lets say we want to provide a button to draw a horizontal rule in the editor – it can be done by making use of the CustomButton() support in the editor. Here is the code to do that:

Here is the output of the above code changes:

image

Fig 5: Custom Button in Tool Bar

Adding Snippets:

Snippets are short piece of text and can be anything. For e.g. an email signature is a text snippet we normally create and store in our mail programs. The mail programs inserts the signature whenever we compose new mail. Similarly Kendo Editor provides ability to create snippets and enable end users to pick the snippet to insert as text. Following is the code:

Here is the output of the above code changes:

image

Fig 6: Snippets Feature

Custom Styling of content:

So far we have seen some of the core functionality of the editor. Another awesome feature of editor is the support for custom styling to the content. You can pretty much define your own style classes and within the editor provide it like a drop down option. Editor supports Styles() option to provide the custom style. Here is the code to achieve this:

If you look at the code what we have done is, created 3 styles for the demo sake and created a new stylesheet named editorStyles.css. We use the Styles() options to add the custom styles and use the Stylesheets() option to add reference to EditorStyles.css. Note the styling Kendo has added to Styles drop down. while setting it up – we just had given a text value pair for a style. Kendo applies the style for the drop down item – neat I say. Here is the output of the above code changes:

image

Fig 7: Custom Styling of content

Handling client side events:

Kendo widgets being client side controls, we have very rich API support on the client side. One of the API feature is that of client side event handling. Editor supports the following events:

  • change – Fires when Editor is blurred and its content has changed
  • execute – Fires when an Editor command is executed
  • paste – Fires before when content is pasted in the Editor
  • select – Fires when the Editor selection has changed

Here is the code to hook on to the client events for the editor:

Here is the output of the above code changes:

image

Fig 8: JavaScript Event Handling

Accessing Editor from client side:

As mentioned in the previous section all Kendo widgets support a rich API and once instantiated we can grab the control at runtime. Here is the JavaScript code do that:

As you can see, on document ready we grab the element which has the id kEditor and then use jquery’s data() method to get the Kendo Editor component. After that we set the content of the editor using the value() method. The client side API support a rich set of methods, properties and events. For a complete API listing, check out our docs page: Kendo Editor API.

Summary:

In this post we looked at one more wrapper namely Editor. It is very easy to work with Editor ASP.NET MVC wrapper and with just couple of lines we have a fully working editor set up. Also we saw how the control supports a rich set of client side API to work with. Hope this post helps you with your endeavor on Kendo Editor.

image.png

Kendo DropDownList Wrapper for ASP.NET MVC

Overview:

This is the sixth post in the series on Kendo UI wrappers for ASP.NET MVC. We will look at one more wrapper in this post namely DropDownList. This post is part of a getting started with Kendo UI wrappers for ASP.NET MVC and you can find the index post here.

What is DropDownList Wrapper?

First lets understand what is a DropDownList control. A DropDownList displays a list of values and allows the selection of a single value from the list. Custom values are not allowed i.e. user cannot type in a custom value rather he can only select from the list.

image

The DropDownList Wrapper for ASP.NET MVC is a server side wrapper for Kendo UI DropDownList which is a JavaScript based widget.

Basic Usage:

In order to instantiate a DropDownList wrapper on any webpage, we make use of the DropDownList extension available within the Kendo helpers. Here is the code which will create a DropDownList control:

 
@( Html.Kendo().DropDownList().Name("kdropdownlist") ) 

Here is the output of the above code:

image

The Name is a required setting on the control. Without that setting we will get error, so provide a unique name every time you instantiate the drop down list control.

Data Binding Scenarios:

The data binding options available for drop down list wrapper are Server binding and Ajax binding. We will look at them one by one.

Server Data Binding:

Lets start by creating an action method. We will build a static list of SelectListItem and pass it as the Model to the view. Here is the code to illustrate that:

 
public ActionResult DropDownList() 
{ 
var items = new List() 
{ 
new SelectListItem { Value="1", Text="Beverages" }, 
new SelectListItem { Value="2", Text="Condiments" }, 
new SelectListItem { Value="3", Text="Confectionries" }, 
new SelectListItem { Value="4", Text="Dairy" }
}; 
return View(items); 
} 

Next we will see how we bind the model data to the drop down list wrapper. Here is the Razor view code:

 
@model List<SelectListItem> 
@( 
   Html.Kendo().DropDownList().Name("kdropdownlist") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .BindTo(Model) 
               .OptionLabel("Select a category") 
) 

As you can see we first let the view know what is the model type it will be working with i.e. the view is now strongly typed. In this case we have a List<SelecteListItem>. Then we use the BindTo() method of the drop down list helper to bind the control with data. We also need to set what is the Text field and Value field to bind too within the model. Now if we run this code, following is result we get:

image

Notice the use of OptionsLabel() method. This lets you add a empty item before any of the data items from the model. So this is like a placeholder or a cue to the user as to what he needs to do.

Ajax Data Binding:

In this section we will see how to bind the drop down list using an Ajax call. First lets create an action method which returns JsonResult instead of ActionResult. The action method will convert the category list which we saw in the server binding as a Json object and return it. Here is the code to illustrate the action method:

 
public JsonResult GetCategories() 
{ 
   var items = new List() 
   { 
      new SelectListItem { Value="1", Text="Beverages" }, 
      new SelectListItem { Value="2", Text="Condiments" }, 
      new SelectListItem { Value="3", Text="Confectionries" }, 
      new SelectListItem { Value="4", Text="Dairy" } 
   }; 
    return Json(items, JsonRequestBehavior.AllowGet); 
} 

We just create the data as we would prepare and then use the Json() method to convert the objects to Json format and return that. Now we will see how to make AJAX call to bind the drop down list with data. Here is the code for the same:

 
@( 
   Html.Kendo().DropDownList() 
               .Name("kdropdownlistajax") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .DataSource(source => 
               { 
                 source.Read(read => { read.Action("GetCategoriesAjax", "Home"); }); 
               }) 
               .OptionLabel("Select a category") 
) 

Instead of using the BindTo() method, we make use of DataSource() method. Within the datasource method we set the read action i.e. what is the action on a controller which will provide us the Json data. With this setting we are not binding the data at the server side, rather the data is bound on the client side.

You will not find any difference when you run the application. But when you do the network sniffing you will see that the control issues a AJAX call to the action method configured for read purpose. Here is a screen shot of the network activity of the page:

SNAGHTML3df1d34a

So we saw how we can use either the server side data binding or client side data binding through AJAX. Depending on your scenario you can take any of the approaches.

Customizing Item Templates:

In the above sections we saw that the Items of the drop down list were just shown as text. With Kendo DropDownList it is possible to customize item templates. The item templates will be visible when the drop down list is in open state. When it is in collapsed state the drop down list will just show the  text field that is bound to the data object. In our example lets say we have images for each of the category and when the drop down list is open we would like to show image next to each of the category name. We can do that easily my making use of the Template() method. You can provide any HTML template and customize each item appearance. Since the templates are pure HTML, Kendo provides a special syntax to access the properties on the bound data object. The syntax is ${<PropertyName>}. That’s it and you can refer the properties of the data item within your custom templates. Here is the code which illustrates the custom teamplate implementation:

 
@( 
   Html.Kendo().DropDownList() 
               .Name("kdropdownlist") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .BindTo(Model) 
               .Template("<img alt='' src='" + Url.Content("~/Images/") + "${Text}.gif' width='40' height='40' />" + 
                         "<span style='padding: 10px;'>${Text}</span>") 
) 

The template is self explanatory. We have image tag whose source is set to an image url formed by using the text of the item itself and then we are showing the text as is. This is a simple template, but the power of template allows you to customize the UI to your needs.

Cascading DropDownList:

One of the common scenarios on web is to cascade a dropdownlist based on a value selected in another dropdownlist. For e.g. I want to show categories dropdown and products dropdowb but the products dropdown should not be enabled until user selects a value in category dropdown. Once a category is selected the products dropdown should get enabled and display all products belonging to that category. With Kendo DropDownList this can be achieved very easily. For the purpose of this example, we will created one more action method GetProductsAjax() which accepts a categoryid and will return products based on the category selected from this action. Here is the code for the same:

 
public JsonResult GetProductsAjax(string categoryId) 
{ 
   var items = new List() 
   { 
      new SelectListItem { Value=categoryId + "1", Text="Product 1" + categoryId }, 
      new SelectListItem { Value=categoryId + "2", Text="Product 2" + categoryId }, 
      new SelectListItem { Value=categoryId + "3", Text="Product 3" + categoryId }, 
      new SelectListItem { Value=categoryId + "4", Text="Product 4" + categoryId } 
   }; 
   return Json(items, JsonRequestBehavior.AllowGet); 
} 

I am just building a static list of products for the demo purpose.

next we will see how we can cascade a product dropdownlist based on category dropdownlist. We will place 2 dropdownlist on the screen – one for category and another for product. Here is the view code:

Category DropDownList:

 
@(
   Html.Kendo().DropDownList() 
               .Name("categories") 
               .OptionLabel("Select category...") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .DataSource(source => 
                          { source.Read(read => { read.Action("GetCategoriesAjax", "Home"); }); }
                          ) 
) 

Products DropDownList:

 
@(
   Html.Kendo().DropDownList() 
               .Name("products") 
               .OptionLabel("Select product...") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .DataSource(source => 
                          { 
                             source.Read(read => { read.Action("GetProductsAjax", "Home") 
                                   .Data("filterProducts"); 
                          }) 
               .ServerFiltering(true); }) 
               .Enable(false) 
               .AutoBind(false) 
               .CascadeFrom("categories") 
)
<script>
   function filterProducts() 
   {
      return {categoryId: $("#categories").val()};
   }
</script>

Notice couple of things in products drop down list. Firstly, in the data source read, we use a Data() method to pass additional data for the request. In this case, we invoke a javascript function which extracts the value of the selected category and pass it to the request. Then we set a property on the drop down list called AutoBind() which controls if the control should fetch the data on load of the control. In our case since we need to wait till a category is selected, we set auto bind to false. Lastly we set a property called CascadeFrom() and pass the parent drop down list id. This property takes care of keeping the products drop down in sync with the category selected. This will also control the enabling and disabling of product drop down based on whether a value is selected in category drop down or not. Here is the out put of the above code:

image

Handling Events:

DropDownList exposes 4 main events on the client side. You can subscribe to those events and perform your business logic if any. The event exposed are as follows:

  • Select – When a item is selected
  • Change – When the value of the drop down is changed
  • Open – When the drop down list is opened
  • Close – When the drop down list is closed

Here is the code to subscribe to these events:

 
@( 
    Html.Kendo().DropDownList() 
                .Name("kdropdownlist") 
                .DataTextField("Text") 
                .DataValueField("Value") 
                .BindTo(Model) 
                .Events(e => { e.Change("change") .Select("select") .Open("open") .Close("close"); })) 
) 

In the above code we use the Events() method to subscribe to different events. The events like Select, Open, Close, Change receive the names of the JavaScript function and when the event occurs the function will be invoked. Here is the JavaScript functions which log the event as it occurs to a div.


<div class="console"></div>

function open() {
        $(".console").html("<p>event: open</p>");
};

function close() 
{
        $(".console").append("<p>event: close</p>");
};

function change() 
{
        $(".console").append("<p>event: change</p>");
};

function dataBound() 
{
        $(".console").append("<p>event: dataBound</p>");
};

function select(e) 
{
        var dataItem = this.dataItem(e.item.index());
        $(".console").append("event :: select (" + dataItem.Text + " : " + dataItem.Value + ")");
};

DropDownList API:

So far we have seen how to get the drop down list instantiated on the screen, bind data and react to events. What if we need to access the drop down list control on the client side, at run time. All Kendo controls provide a very rich client side API. Using these api’s we can access a control which is already instantiated on the screen using JavaScript. Here is the code to access a drop down list control from JavaScript:

 
$(document).ready(function()
{ 
   var dropdownlist = $("#kdropdownlist").data("kendoDropDownList") 
}); 

On document ready, we use the jquery selector syntax to grab a element with id kdropdownlist and then use the jquery’s data() method to get the kendo drop down object. After this we can perform many of the operation exposed by the object. The methods supported by the drop down list is as follows:

close() closes the drop down list
dataItem() returns raw data record at the specified index
destroy() prepare for safe removal from DOM
enable(bool) enables/disables drop down list
open() opens the drop down list
refresh re-renders items in the list
search(string) selects item which starts with provided parameter
select(jquery|Number|function) selects item and sets the value & text
setDataSource(datasource) sets datasource and rebinds the drop down list
text(string) gets/sets the text of the drop down
toggle(bool) toggles between open & closed states
value(string) gets/sets the value of the drop down

Summary:

In this post we looked at one more commonly used controls – DropDownList. With the ASP.NET wrappers we saw how easy it is to instantiate a control, perform server side or ajax data binding and then how to work with the client side API. Hope you find this useful. Do give it a try i.e. download Kendo Complete and get started with Kendo Wrappers for ASP.NET MVC.

image_thumb.png

Kendo DateTimePicker Wrapper for ASP.NET MVC

Overview:

This is the fifth post in a series on Kendo UI wrappers for ASP.NET MVC. In this post we will look at one more wrapper named DateTimePicker. Before we get on with DateTimePicker Kendo wrapper, if you are new and want to learn more about Kendo Wrappers for ASP.NET MVC, I suggest you take a look at “Jumpstarting Development with Kendo UI for ASP.NET MVC” by Abhishek Kant. The jumpstarting blog post will give you the basics on how to get started with Kendo for ASP.NET MVC. Here is the post which has links to all other blog post of the series.

What is DateTimePicker control?

DateTimePicker is a control which allows end user to select a date & time from a calendar & time picker. It also supports to input the data directly. The DateTimePicker control supports customizing the month view by providing a custom template. The Minimum date, Maximum date, the view to start the calendar with and the time interval on the time picker, are all configurable through options.

image

Instantiating a DateTimePicker:

The first step in using a date time picker is to instantiate it on the page. To instantiate the control we make use of the DateTimePicker builder available as part of the Kendo Wrappers for ASP.NET MVC. Below is the code snippet which shows how to instantiate the control:


@(
Html.Kendo().DateTimePicker()
.Name("kdatetimepicker")
.HtmlAttributes(new { style = "width:230px"})
 )

Here is the output of the above code:

image

What we just did was to instantiate a DateTimePicker control on the page and we gave it name. When it is rendered you will basically see a textbox to enter the date and time, a calendar button and the clock button. The calendar button when clicked will allow you to select a date and when you click the clock button will allow you to select the time interval.

Set default value to control:

As you can see from the previous section, when the control is instantiated the textbox is empty. That is expected as we never set a default value to the date time picker control. The calendar when opened will always show the current date highlighted but that is not a value until use clicks on it. In order to set the default value on the control, we will use the Value() method. The Value() method takes DateTime instance or a date in string format, which will be set as the controls value. Here is the code snippet to set the default value:


@(
Html.Kendo().DateTimePicker()
.Name("kdatetimepicker")
.Value("12/12/2012 14:30")
.HtmlAttributes(new { style = "width:230px"})
)

And here is the output of the above code snippet:

image

Formatting controls value:

Previous section we saw how to set the value of the control. The default format in which the date and time is displayed is “MM/dd/yyyy hh:mm tt” i.e. Month, Day, Year, Hour, Minutes and Meridian. Lets say we want to change the format in which the date and time is shown. The control provides the options to modify the format through Format() method. The Format() method takes a string which is nothing but your new format for date and time display. Here is a code snippet to set the format:


@(
Html.Kendo().DateTimePicker()
.Name("kdatetimepicker")
.Value("12/12/2012 14:33")
.Format("On MM/dd/yyyy @ hh:mm tt")
.HtmlAttributes(new { style = "width:240px"})
)

Here is the output of the above code change:

image

As you cane see I just provided a format “On MM/dd/yyyy @ hh:mm tt” and this translates the value to “On 12/12/2012 @ 02:33 PM”. So this is a handy setting to keep in mind.

Putting constraints on date selection:

With date picker, one of the common requirement that you will have to take care is to restrict the dates a user can select. You may want to set a minimum date and maximum date restriction on the calendar itself. The date time picker control provides this option through Min() and Max() methods. Both Min and Max methods support two overloads – one takes a string format of a date and another takes an instance of DateTime. Here is the code snippet to put restrictions on the calendar:


@(
Html.Kendo().DateTimePicker()
.Name("kdatetimepicker")
.Value("12/12/2012 14:33")
.Min("12/10/2012").Max("12/21/2012")
.Format("On MM/dd/yyyy @ hh:mm tt")
.HtmlAttributes(new { style = "width:240px"})
)

image

As you can see the dates are now restricted and the user can select from only the dates allowed to select.

Setting the Time interval:

The time picker component in this control, by default, sets the time interval between hours to 30 minutes. You have the flexibility to control the interval between the hours by using the Interval() method. The Interval() method takes a integer and will set the interval based on this value. Lets say I want to set the interval to 15 minutes, find below the code snippet to do that:


@(
Html.Kendo().DateTimePicker()
.Name("kdatetimepicker")
.Value("12/12/2012 14:30")
.Min("12/10/2012").Max("12/21/2012")
.Interval(15)
.Format("On MM/dd/yyyy @ hh:mm tt")
.HtmlAttributes(new { style = "width:240px"})
)

And here is the output of the above code snippet:

image

As you can see the interval between the hour is now set to 15 minute interval and this is through the Interval() setting we have in the code.

Handling Events:

The date time picker control supports client side event handling. The control exposes 3 events namely Open, Close and Change. Note that all these are client side events and the handlers will be client side event handlers. Here is the code snippet to listen to events and provide the event handlers to those events:


@(
Html.Kendo().DateTimePicker()
.Name("kdatetimepicker")
.Value("12/12/2012 14:30")
.Min("12/10/2012").Max("12/21/2012")
.Interval(15)
.Format("On MM/dd/yyyy @ hh:mm tt")
.HtmlAttributes(new { style = "width:240px"})
.Events(e => e
.Open("kdatetimepicker_open")
.Change("kdatetimepicker_change")
.Close("kdatetimepicker_close")
)
)

<script>
function kdatetimepicker_open() {
//Handle the open event
}

function kdatetimepicker_close() {
//Handle the close event
}

function kdatetimepicker_change() {
//Handle the change event
}
</script>

Access control from client side:

So far we have seen how to instantiate and configure settings on the control from server side. And the configuration was done using the Kendo ASP.NET MVC wrapper. Once the control is rendered on the client side what if you need to perform some operation on the DateTimePicker control itself. The Kendo UI JavaScript APIs allow us to grab the control on the client side and access its properties and methods. Let’s say on date change by user, we want to get the newly selected value and prompt it. Here is the code snippet to do that:


@(
Html.Kendo().DateTimePicker()
.Name("kdatetimepicker")
.Value("12/12/2012 14:30")
.Min("12/10/2012").Max("12/21/2012")
.Interval(15)
.Format("On MM/dd/yyyy @ hh:mm tt")
.HtmlAttributes(new { style = "width:240px"})
.Events(e => e
.Change("kdatetimepicker_change")
)
)
<script>
function kdatetimepicker_change() {
var dateTimePicker = $("#kdatetimepicker").data("kendoDateTimePicker");
alert(dateTimePicker.value());
}
</script>

As you can see, we first listen to on change event and in the event handler for change we use jquery selector to get the element by its id and use the jquery data() method to get the Kendo DateTimePicker control. Once we get hold of the control, it supports the value() method which will give us the current selected value. Here is the output of the above code:

image

Summary:

In this post we looked at one more Kendo Wrapper namely DateTimePicker. This control makes a perfect match for scenarios where you need to present both the date and time selection. We saw how easy it was to work with the control from the server side. With just a few settings we can get this control working according to our needs.

image_thumb.png

Kendo DatePicker Wrapper for ASP.NET MVC

Overview:

This is the fourth post in a series on Kendo UI wrappers for ASP.NET MVC. In this post we will look at one more wrapper named DatePicker. Before we get on with DatePicker Kendo wrapper, if you are new and want to learn more about Kendo Wrappers for ASP.NET MVC, I suggest you take a look at “Jumpstarting Development with Kendo UI for ASP.NET MVC” by Abhishek Kant. The jumpstarting blog post will give you the basics on how to get started with Kendo for ASP.NET MVC. Here is the post which has links to all other blog post of the series.

What is DatePicker control?

DatePicker is a control which allows end user to select a date from a calendar or by inputting the data directly. The DatePicker control supports customizing the month view by providing a custom template. The Minimum date, Maximum date and the view to start out with are all configurable through options.

image

Instantiating a DatePicker:

to instantiate a DatePicker control on the page, we make use of the DatePicker builder available in as part of the Kendo wrapper helpers. Take a look at the below code to see how DatePicker is instantiated:

@( Html.Kendo().DatePicker().Name("kdatepicker") )

Here is the output of the above code:

image

As you can see we just instantiated the DatePicker control on the page. The control is made up of the textbox for manual input and a button (having calendar icon) which when clicked will bring up a calendar so that user can select any date.

Setting default value at instantiation:

In the previous section we saw how to instantiate a DatePicker control. But when it was rendered we did not see any default value i.e. a default date being displayed in the textbox. Well, that is because we never told the control what its default value was. DatePicker control exposes a method called Value() which can be used to set the default value. Here is a code to set the default value of the control to current day:

@(Html.Kendo().DatePicker().Name("kdatepicker")
      .Value(DateTime.Today)
)

Here is the output as a result of setting the default value to the control:

image

Formatting selected value:

We saw how to set the default value of the date picker control. The default format in which the date value is shown is MM/DD/YYYY. If you want to customize the format, the control provides the option to use the Format() method and provide any valid date time format that we are familiar with. So here is the code to set the format as “<Day Name>, <Month Name> <Date>, <Year>”:

@(Html.Kendo().DatePicker().Name("kdatepicker")
      .Value(DateTime.Today)
      .Format("dddd, MMMM dd, yyyy")
      .HtmlAttributes(new { style = "width:230px"})
)

I have used the Format() method and passed in a format “dddd, MMMM dd, yyyy” and below is the output of that code:

image

Putting constraints for selection:

When using date pickers in a real world applications, one of the common scenario is to restrict the dates a user can select. Usually we will have a minimum date and maximum date range and we would like the calendar to show only those dates and user can select only from those dates. DatePicker control provides Min() and Max() method which accept a DateTime value and use these two settings to restrict the values. Here is the code to use the Min & Max methods. I am setting the minimum date to be today and maximum date to be 4 days from today:

@(Html.Kendo().DatePicker().Name("kdatepicker")
      .Value(DateTime.Today)
      .Format("dddd, MMMM dd, yyyy")
      .Min(DateTime.Today)
      .Max(DateTime.Today.AddDays(4))
      .HtmlAttributes(new { style = "width:230px"})
)

Here is the output of the above code:

image

Customizing the Calendar Views:

So far we have seen that when the calendar is used for selecting a date, by default it shows the month view i.e. it shows current month and the days in that month. DatePicker control also has the provision to customize the calendar view and we can do that by using the Start() method. The Start() method accepts a enum of type CalendarView. CalendarView has options Century, Decade, Month and Year. You just set what view you would like to see and the calendar will show that particular view every time users open the calendar.  Here is a code to set the start view of the calendar to Century:

@(Html.Kendo().DatePicker().Name("kdatepicker")
      .Value(DateTime.Today)
      .Format("dddd, MMMM dd, yyyy")
      .Start(CalendarView.Century)
      .HtmlAttributes(new { style = "width:230px"}) )

Here is the output for the same:

image

Here is an example of all the calendar views:

image

Customizing cell rendering:

Imagine a scenario where you want to customize how a particular day needs to be rendered on the calendar. For e.g. November 9 is my birthday. So whenever Nov 9 is rendered I want to be reminded that its my birthday and I want a cake icon to be shown on that day. For such a scenario, DatePicker control has the provision to customize each cell rendering. This is done by passing a template to a method named MonthTemplate(). You can pass any valid kendo template string to this method. Here is the code to show a birthday cake on Nov 9 of every year:

@(Html.Kendo().DatePicker().Name("kdatepicker")
.Value(DateTime.Today)
.Format("dddd, MMMM dd, yyyy")
.HtmlAttributes(new { style = "width:230px"})
.MonthTemplate(" # if (data.value == 9 && data.date.getMonth() == 10) { # " +
"<div class=birthday /> " +
"# } #  " +
"#= data.value #")
)

What I have done is to pass a template string. If you look at the template itself, I am just checking if the current rendered date is 9 and current rendering month is November (remember JavaScript month array is zero index based, so Nov = 10) and if yes I am showing a div with class birthday. The stylesheet for birthday just puts a cake image. We show the date value irrespective of the check we do. Here is the output of the above code:

image

Customizing the footer:

When the calendar is open, it usually shows the current day in “<Day Name>, <Month Name> <Date>, <Year>” format at the bottom. This is known as the footer. This footer can be customized by providing a custom template. Here is the code to customize the footer:

@(Html.Kendo().DatePicker().Name("kdatepicker")
.Value(DateTime.Today)
.Format("dddd, MMMM dd, yyyy")
.HtmlAttributes(new { style = "width:230px"})
.Footer("Today - #= kendo.toString(data,'ddd, MMM dd, yyyy') # ")
)

Here is the output of the same:

image

Summary:

In this post, we looked at one more Kendo Wrapper named DatePicker. We looked at how easy it is to instantiate the control. set a default value, formatting the selected value, restricting the dates that can be picked, customizing the calendar view, customizing the cell rendering and finally how to customize the footer of the calendar. Hope this gives you a jumpstart at developing with Kendo DatePicker wrapper for ASP.NET MVC.

Till next time – Happy Coding!

image_thumb.png

Kendo ComboBox Wrapper for ASP.NET MVC

Overview:

In this third post on Kendo UI Wrapper for ASP.NET MVC, we will look at one more wrapper named ComboBox. If you are new to Kendo UI Wrappers for ASP.NET MVC, I suggest that you go through “Jumpstarting Development with Kendo UI for ASP.NET MVC” by Abhishek Kant. This post, as the name suggests will give you a jumpstart on Kendo UI Wrappers for ASP.NET MVC. Lets go ahead and look at the ComboBox Wrapper in detail. If you are looking for the index post on this getting started series, click here.

What is The ComboBox control?

The ComboBox control displays a list of values and allows the selection of a single value from this list. Custom values may also be entered via keyboard input. If you do not wish permit keyboard input – that is, custom values are not permitted – use the DropDownList.

The ComboBox represents a richer version of a <select>element, providing support for local and remote data binding, item templates, and configurable options for controlling the list behavior.

image

Instantiating a ComboBox:

To instantiate a ComboBox on any page, we make use of the ComboBox builder available within the Kendo helper. See below the code snippet to instantiate a combobox:

   1: @(

   2:     Html.Kendo().ComboBox().Name("kcombobox")

   3: )

That’s it to get a combobox control on the page. Note that the Name is mandatory to be set on the wrapper. This makes the ID of the combobox when rendered on the client side. Here is the output of our code:

image

As you can see the combobox control is created on the page. But we don’t see anything happening yet because we haven’t bound any data to the control. we will see data binding option in a minute.

Providing a Placeholder:

ComboBox wrapper, similar to that of AutoComplete wrapper provides an option to put a placeholder text in the control when there is no value selected by the user. The placeholder will be displayed only when user has not made any choice; once he  makes a choice the placeholder text will not be shown instead the text of the selected item will be shown. We set placeholder using the Placeholder() method which accepts the string to be displayed as placeholder. Here is the code snippet:

   1: @(

   2:     Html.Kendo().ComboBox().Name("kcombobox")

   3:     .Placeholder("Select a value...")

   4: )

And here is the output of the above code:

image

Providing Data Source:

So far we have been able to get the combobo on to the page with the instantiation code. Now we will see how to provide data to the combobox. The data source can be provided in three ways and they are:

  • BindTo – using BindTo() method, any IEnumerable data can be bound
  • Items – using Items() method, define items
  • DataSource – using the DataSource() method, define action method and controller to fetch data

Using BindTo() for data binding:

BindTo() method allows you to provide data to the Combobox control right at the time of instantiating the control. BindTo() method accepts any data items which is of type IEnumerable. Lets say we have a string of text to show in the combobox, we can write the code as below:

   1: @(

   2:             Html.Kendo().ComboBox().Name("kcombobox")

   3:             .Placeholder("Select a value...")

   4:             .BindTo(new string[] {"Bulgaria",

   5:                                   "United States",

   6:                                   "India","Australia",

   7:                                   "United Kingdom"}

   8:                    )

   9:  )

As you can see, we just create a string array and bind it to the control. Here is the output of the above code:

image

Normally a combobox is used to show a lookup list where in the text inside the control is usually for the end user readability, where as the value stored in the database is usually an integer. So if your data source is a complex object and you want to show text and maintain value in the backend, you would need to set 2 extra properties for this to work correctly. They are DataTextField & DataValueField. Here is the code snippet to achieve this:

   1: @(

   2:             Html.Kendo().ComboBox().Name("kcombobox")

   3:             .HtmlAttributes(new { style = "width:250px"})

   4:             .Placeholder("Select a value...")

   5:             .DataTextField("Text")

   6:             .DataValueField("Value")

   7:             .BindTo(new List<SelectListItem>() {

   8:                           new SelectListItem() {

   9:                             Text = "Bulgaria", Value = "1"

  10:                           },

  11:                           new SelectListItem() {

  12:                             Text = "Unites States of America", Value = "2"

  13:                           },

  14:                           new SelectListItem() {

  15:                             Text = "India", Value = "3"

  16:                           },

  17:                           new SelectListItem() {

  18:                             Text = "Australia", Value = "4"

  19:                           },

  20:                           new SelectListItem() {

  21:                             Text = "United Kingdom", Value = "5"

  22:                           }

  23:                       }

  24:                  )

  25:         )

In the above code snippet we create a new list of SelectListItem, bind it to the control and let the control know which property should be used to show the text & which property should be used to store the value of the selected item. The output will have no change as compared to previous example.

Using Items() for data binding:

Items() method allows you to define the items of the combobox control at the time of instantiating the control. If you ever have a scenario where the data to be bound to the control is static but you still need the flexibility of displaying text/value pair, you can use the Items() method. Here is the code snippet to use the Items() method:

   1: @(

   2:             Html.Kendo().ComboBox().Name("kcombobox")

   3:             .HtmlAttributes(new { style = "width:250px" })

   4:             .Placeholder("Select a value...")

   5:             .DataTextField("Text")

   6:             .DataValueField("Value")

   7:             .Items(item =>

   8:                     {

   9:                         item.Add().Text("Bulgaria").Value("1");

  10:                         item.Add().Text("United States Of America").Value("2");

  11:                         item.Add().Text("India").Value("3");

  12:                         item.Add().Text("Australia").Value("4");

  13:                         item.Add().Text("United Kindom").Value("5");

  14:                     }

  15:             )

  16:         )

The output again will be the same as previous output.

Using DataSource() for data binding:

If you want to get the data for combobox from a controllers action method, you will need to use DataSource() method. This allows you to set the controller name and the action name from which the data will be retrieved at runtime by issuing an AJAX request. First lets look at the controller action method:

   1: public JsonResult GetCountries()

   2:         {

   3:             var countries = new List<SelectListItem>

   4:                             {

   5:                                 new SelectListItem{Text ="Bulgaria",

   6:                                                    Value="1"},

   7:                                 new SelectListItem{Text ="United States of America",

   8:                                                    Value="2"},

   9:                                 new SelectListItem{Text ="India",

  10:                                                    Value="3"},

  11:                                 new SelectListItem{Text ="Australia",

  12:                                                    Value="4"},

  13:                                 new SelectListItem{Text ="United Kingdom",

  14:                                                    Value="5"},

  15:                             };

  16:             return Json(countries, JsonRequestBehavior.AllowGet);

  17:         }

The action method is a standard action method and the only difference is that it is returning a JsonResult. This is because the control will issue a AJAX request on loading on the client side to fetch the data. Now here is the code snippet to instantiate the control:

   1: @(

   2:             Html.Kendo().ComboBox().Name("kcombobox")

   3:             .HtmlAttributes(new { style = "width:250px" })

   4:             .Placeholder("Select a value...")

   5:             .DataTextField("Text")

   6:             .DataValueField("Value")

   7:             .DataSource(source =>

   8:             {

   9:                 source.Read(read =>

  10:                 {

  11:                     read.Action("GetCountries", "Home");

  12:                 });

  13:             })

  14:         )

Pay attention to the DataSource() method declaration. We are providing it a configurator which knows what is the read URL to fetch the data. We are just providing the controller

& action name. The control will automatically issue a AJAX request to get the data as a JSON payload.

Serverside Filtering:

If we don’t specify any filter strategy i.e. server or client, the combobox control will use the client side filtering by default. If we have huge list then it is wise to filter the data on the server instead of sending everything to client and then filter on the client side. For the server side filtering to work, we should first set the filter type and then enable the ServerSideFiltering flag on the data source itself.  We can set the filter options with valid values equal to “StartsWith” or “Contains”. Here is the action method which depicts the server side filtering:

   1: public JsonResult GetCountries(string text)

   2:         {

   3:             var countries = new List<SelectListItem>

   4:                             {

   5:                                 new SelectListItem{Text ="Bulgaria",

   6:                                                    Value="1"},

   7:                                 new SelectListItem{Text ="United States of America",

   8:                                                    Value="2"},

   9:                                 new SelectListItem{Text ="India",

  10:                                                    Value="3"},

  11:                                 new SelectListItem{Text ="Australia",

  12:                                                    Value="4"},

  13:                                 new SelectListItem{Text ="United Kingdom",

  14:                                                    Value="5"},

  15:                             };

  16:             if (!string.IsNullOrEmpty(text))

  17:             {

  18:                 countries = (from item in countries

  19:                              where item.Text.StartsWith(text)

  20:                              select item).ToList();

  21:             }

  22:             return Json(countries, JsonRequestBehavior.AllowGet);

  23:         }

Here is the combobox definition:

   1: @(

   2:             Html.Kendo().ComboBox().Name("kcombobox")

   3:             .HtmlAttributes(new { style = "width:250px" })

   4:             .Placeholder("Select a value...")

   5:             .DataTextField("Text")

   6:             .DataValueField("Value")

   7:             .Filter(FilterType.StartsWith)

   8:             .DataSource(source =>

   9:             {

  10:                 source.Read(read =>

  11:                 {

  12:                     read.Action("GetCountries", "Home");

  13:                 }).ServerFiltering(true);

  14:             })

  15:             .Template("<span><img src='/Content/Images/${data.Value}.jpg' " +

  16:                             "width='20' height='20' />&nbsp;${data.Text}</span>")

  17:         )

 

Controlling the data binding:

The items of the combobox control will be queries as soon as the control is instantiated on the client side. If you do not wish to go with this behavior, the control provides a mechanism to control when to load the items. You can set the control to load the items either user types in the combobox or when he open the options list. This is possible due to a method called AutoBind(). This takes a boolean value to indicate whether to load data on instantiation or wait for the user interaction with the control. Here is the code snippet to set this behavior:

   1: @(

   2:             Html.Kendo().ComboBox().Name("kcombobox")

   3:             .HtmlAttributes(new { style = "width:250px" })

   4:             .Placeholder("Select a value...")

   5:             .DataTextField("Text")

   6:             .DataValueField("Value")

   7:             .Filter(FilterType.StartsWith)

   8:             .DataSource(source =>

   9:             {

  10:                 source.Read(read =>

  11:                 {

  12:                     read.Action("GetCountries", "Home");

  13:                 }).ServerFiltering(true);

  14:             })

  15:             .Template("<span><img src='/Content/Images/${data.Value}.jpg' " +

  16:                             "width='20' height='20' />&nbsp;${data.Text}</span>")

  17:             .AutoBind(false)

  18:         )

Custom templates for combobox item display:

Consider a scenario where in you want to customize the combobox item display on the client side. i.e. let us say we want to show the country flag before the country name which is displayed as a text of the combobox item. Well, the control provides a way to provide our custom template which will be used for display on the client side. The Template() method accepts a HTML markup which will be used to display the item instead of the default template the control uses. You access data item using the {data.<property name>} syntax inside the custom template markup. Here is the code snippet to work with Template() method:

   1: @(

   2:             Html.Kendo().ComboBox().Name("kcombobox")

   3:             .HtmlAttributes(new { style = "width:250px" })

   4:             .Placeholder("Select a value...")

   5:             .DataTextField("Text")

   6:             .DataValueField("Value")

   7:             .DataSource(source =>

   8:             {

   9:                 source.Read(read =>

  10:                 {

  11:                     read.Action("GetCountries", "Home");

  12:                 });

  13:             })

  14:             .Template("<span><img src='/Content/Images/${data.Value}.jpg' " +

  15:                             "width='20' height='20' />&nbsp;${data.Text}</span>")

  16:         )

Notice the Template() method and the markup inside it. We use {data.Value} to access the value of the bound data item and {data.Text} to access the text of the bound data item. Using this method you can pretty much customize the UI if the comboxbox item.

 

Cascading Comboboxes:

One of the typical scenarios of web is to cascade a child combobox based on the item selected in a parent combobox. for e.g. consider a categories combobox and a products combobox. We want the categories combobox to filled with items first, user should select a category and then the products belonging to that category to be shown. With Kendo Combobox this is fairly simple as it allows a method called CascadeFrom(). As the name goes we just need to pass the parent combobox based on which we need to cascade. To illustrate this, consider that we have 2 action methods named GetCategories() and GetProducts(). For getting the products we need to know the category id. So here is the code snippet for this:

   1: public JsonResult GetCascadeCategories()

   2: {

   3:     var northwind = new NorthwindDataContext();

   4:

   5:     return Json(northwind.Categories.Select(

   6:                 c => new { CategoryId = c.CategoryID,

   7:                 CategoryName = c.CategoryName }),

   8:                 JsonRequestBehavior.AllowGet);

   9: }

   1: public JsonResult GetCascadeProducts(string categories)

   2: {

   3:     var northwind = new NorthwindDataContext();

   4:     var products = northwind.Products.AsQueryable();

   5:

   6:     if (!string.IsNullOrEmpty(categories))

   7:     {

   8:         products = products.Where(p => p.CategoryID.ToString() == categories);

   9:     }

  10:

  11:     return Json(products.Select(p => new {

  12:                 ProductID = p.ProductID,

  13:                 ProductName = p.ProductName}),

  14:                 JsonRequestBehavior.AllowGet);

  15: }

Here is the combobox definition for categories:

   1: @(Html.Kendo().ComboBox()

   2:           .Name("categories")

   3:           .Placeholder("Select category...")

   4:           .DataTextField("CategoryName")

   5:           .DataValueField("CategoryId")

   6:           .DataSource(source => {

   7:                source.Read(read => {

   8:                    read.Action("GetCascadeCategories", "Home");

   9:                });

  10:           })

  11:     )

Here is the combobox definition for Products:

   1: @(Html.Kendo().ComboBox()

   2:           .Name("products")

   3:           .Placeholder("Select product...")

   4:           .DataTextField("ProductName")

   5:           .DataValueField("ProductID")

   6:           .DataSource(source => {

   7:               source.Read(read =>

   8:               {

   9:                   read.Action("GetCascadeProducts", "ComboBox")

  10:                       .Data("filterProducts");

  11:               })

  12:               .ServerFiltering(true);

  13:           })

  14:           .Enable(false)

  15:           .AutoBind(false)

  16:           .CascadeFrom("categories")

  17:     )

  18:     <script>

  19:         function filterProducts() {

  20:             return {

  21:                 categories: $("#categories").val()

  22:             };

  23:         }

  24:     </script>

Note the usage of CascadeFrom() method. We pass in the name of the categories combobox. The AutoBind() is set to false. So these two settings make sure that products combobox is not loaded when no categories is selected. When user selects a category, that’s when products combobox will issue the AJAX request for getting list of products. Since we need to know what category is selected, we make use of the additional data concept on the data source read and pass in the selected categories value. This is done using the filterProducts() javascript method.

Here is the output of the same:

imageimage

Client side access to combobox:

Using the Jquery data() method we can access the Keno Combobox from the client side. You may have a scenario where in you want to load the combobox based on a button click. Here is the code to achieve that:

   1: <script>

   2:     var kendoComboBox = null;

   3:     $(document).ready(function () {

   4:

   5:         kendoComboBox = $("#kcombobox").data("kendoComboBox");

   6:

   7:         $("#button").click(function () {

   8:             kcb.dataSource.read();

   9:         });

  10:     })

  11: </script>

First we declare a global variable which will hold the reference of the combobox. Then on page load we make use of the data() method to get access to the control. On a button click, we just access the dataSource property and issue a read() method on it.

For a complete list of client side API, have a look at this help documentation.

Summary:

In this post, we looked at how easy it is to instantiate a combobox control and set it up for data binding. We also looked at some of the features such as auto bind i.e. control when the data is bound to the control, different ways of data binding the control, cascading based on a item selection of another combobox and last but not the least how to access the combobox from the client side. Hope this gives you a jumpstart at using the Kendo Combobox Wrapper for ASP.NET MVC .

Till next time – Happy Coding!

image_thumb.png

Kendo Calendar Wrapper for ASP.NET MVC

Overview:

In this post we will learn about one more wrapper from Kendo UI library called Calendar. If you are starting new on Kendo UI, make sure to go through the blog post – Jump starting Development with Kendo UI for ASP.NET MVC. We will look at the usage of the Calendar widget and how to program the Calendar widget. If you are looking for the index post on this getting started series, click here.

To follow this blog post, just create a “C# Kendo UI for MVC Web Application” project type and work along.

What is Calendar Widget:

The Calendar Widget renders a graphical calendar that supports navigation and selection. It supports custom templates for its “month” view, configurable options for a minimum and maximum date, start view and the depth of the navigation.

image

Instantiating a Calendar:

To instantiate a Calendar widget on any page, we just make use of the Calendar builder available within the Kendo helper. Here is the code snippet to instantiate a  Calendar:

   1: @(Html.Kendo().Calendar()

   2:               .Name("kcalendar")

   3: )

Note that the “Name” is mandatory setting. This defines the ID of the control on the client side. So here is the output of the code we wrote:

image

That’s it – with just one line of code we have a Calendar on our page. Next lets see how we can control the Calendar View.

Calendar View Settings:

Be default if nothing is said about the view we need to see on the Calendar, it is going to use Month view i.e. the current month is shown in the calendar. The Calendar widget has the following view options to choose from:

  • Century – When selected, Calendar will show decades of the current century
  • Decade – When selected, Calendar will show years of the the current decade
  • Month – When selected, Calendar will show days of the current month
  • Year – When selected, Calendar will show months of the current year

The way we set the view is through a method called Start(). The different view settings are available as a CalendarView enum. Here is the code snippet to set the view of the calendar:

   1: @(Html.Kendo().Calendar()

   2:               .Name("kcalendarCentury")

   3:               .Start(CalendarView.Century)

   4:             )

Here is the output of the above code:

image

Setting Calendar Value:

So far we have been able to instantiate a calendar on the page. But if you notice clearly the current date is not highlighted by default. The current date is displayed at the footer of the calendar but the day is not highlighted. That is because, calendar has a property called Value() and to have a date highlighted this property needs to provided with a DateTime instance. It can be current day or any other day. Here is the code snippet to set the value of the calendar:

   1: @(Html.Kendo().Calendar()

   2:               .Name("kcalendarvalue")

   3:               .Value(DateTime.Today)

   4:  )

All we are doing is setting the Value of the calenda to DateTime.Today instance. Here is output of that code:
image

Setting Calendar Value:
Many a times when using calendar we will have scenarios where we need to restrict the dates that the user can select. For e.g. lets assume that we want to user to select the dates between 19 Nov and 23 Nov only. That means the minimum date that can be selected is 19 Nov and maximum date that can be selected is 23 Nov. Well to achieve this scenario, the calendar provides Min() and Max() property and both of this method accept either a string representing a date  or an instance of DateTime. Here is the code snippet for setting Min & Max property:
   1: @(Html.Kendo().Calendar()

   2:               .Name("kcalendarrestriction")

   3:               .Min("2012/11/19")

   4:               .Max("2012/11/23")

   5:  )

And here is the output of the changes we made:
image
As you can see it does not show the dates outside of the allowed Min and Max date settings.
Accessing Calendar from client side:
You may have a scenario where you want to get hold of the calendar widget from JavaScript. This can be achieved by using the jquery.data() method. Assume that we had named our calendar as “kcalendar”, here is the code snippet to access that from JavaScript:
   1: var calendar = $("#kcalendar").data("kendoCalendar");

As you can see, we just use jquery’s data() syntax to get the Kendo Calendar object. The Kendo controls all have very rich client side API that you can work with. For e.g. if we have to set the value of the calendar from client side you can use the value() method on the control. Here is the code snippet for the same:
   1: var calendar = $("#kcalendar").data("kendoCalendar");

   2: calendar.value(new Date(2012, 0, 1));

Configuring client side events:
Kendo Calendar exposes two client side events which can be hooked into while instantiating the control. The event exposed are:
  • Change – occurs when the value is changed
  • Navigate – occurs when any navigation is performed by the user i.e. month change, year change etc.
When we hook into the events exposed, we just configure the JavaScript function which will handle the event on the client side. Here is the code snippet to handle the value change event of the calendar:
   1: @(Html.Kendo().Calendar()

   2:               .Name("kcalendarevents")

   3:               .Events(evnt => evnt.Change("onValueChange"))

   4:  )

   5: <script>

   6:     function onValueChange(e)

   7:     {

   8:         var kcal = $("#kcalendarevents").data("kendoCalendar");

   9:         alert(kcal.value());

  10:     }

  11: </script>

Similarly you can handle the Navigate event also.
Summary:
Kendo Calendar is yet another wrapper available in the Kendo UI library – which lets you create a graphical calendar on a web page. We saw how simple it is to instantiate on any page. We also saw some of the properties supported by the control. We also saw how to work with the control from client side i.e. from JavaScript. Hope this provides you with a kind of quick start to work with Kendo UI Wrappers. Stay tuned for many more of these posts on Kendo UI Wrapper usage.
Till next time – Happy coding!
image_thumb.png

Kendo AutoComplete Wrapper for ASP.NET MVC

Overview:

This is the first post in the series “Getting Started Series on Kendo UI Wrappers for ASP.NET MVC”. In this post we will look at Kendo AutoComplete wrapper. If you are new to Kendo UI Wrappers for ASP.NET MVC, I suggest that you go through “Jumpstarting Development with Kendo UI for ASP.NET MVC” by Abhishek Kant . This post, as the name suggests will give you a jumpstart on Kendo UI Wrappers for ASP.NET MVC.

image

Lets go ahead and look at the AutoComplete Wrapper in detail.

What is The AutoComplete control?

The AutoComplete control provides suggestions depending on the typed text. It also allows multiple value entries. As the user types, the autocomplete control will suggest items from source that the control is bound to. The user can then select one or many items depending on the configuration. Multiple values will be separated by a delimiter.

image

Creating ASP.NET MVC Project:

If you have installed the Kendo UI Complete using the installer, you will find project templates to create a new ASP.NET MVC project with Kendo UI Wrappers. This template makes it easy to work with wrappers as it sets up all the right references to the assemblies. If you select File > New Project, select Telerik > Web from the installed template and select “C# Kendo UI for MVC Web Application” from the project template and select Ok.

SNAGHTML1af6f00

If you have the extensions but not the installer, then make sure you follow the instructions here to add the assembly’s and correct js/css references.

Instantiating Kendo AutoComplete:

Now that we have created an ASP.NET MVC project, lets see how we can use the Kendo AutoComplete control. For this post, I will be using the Razor syntax and all code will be written in Home/Index view. Now lets instantiate a Kendo AutoComplete control on the page. Here is the code snippet of how that can be done:

@(Html.Kendo().AutoComplete().Name("kautocomplete"))

As you can see we support the Fluent interface so you can chain the calls. All we have done here is to use the Kendo helper and instantiate an AutoComplete. Technically the AutoComplete() is actually a builder which knows how to spit out the Kendo AutoComplete UI js/css on the client side. One more thing that is necessary is to name the control. So we use the Name() method to provide a name to the control. With the above lines placed, we see the following output:

SNAGHTML218a5ab

Providing a Place Holder:

Placeholder is nothing but a default text that will be shown on the control when no value is selected by the user. The AutoComplete supports a PlaceHolder() method which takes a text as input. Here is a code snippet of how to use the Placeholder:

   1: @(

   2:     Html.Kendo().AutoComplete()

   3:                 .Name("kautocomplete")

   4:                 .Placeholder("Select contry...")

   5: )

The output will be as below’:

SNAGHTML2206ea5

Providing Data Source to AutoComplete control:

Now that we have the auto complete on the page lets do some data binding to the control. Currently it does nothing as it does not have a data source to work with. We can provide data in two ways.

  • Provide a data at the time of instantiating the control using the BindTo() method
  • Hooking up a controller action method which will provide data using DataSource() option.

Data binding using BindTo() method:

The signature of BindTo() method is as below:

image

The input to BindTo() method is an IEnumerable, which means you can just pass any IEnumerable data you may have during the instantiation itself and the control will be bound to that. For instance say we want to bind the auto complete control to list of country names which are held in string array. Here is the code snippet to do that:

   1: @(

   2:     Html.Kendo().AutoComplete()

   3:                 .Name("kautocomplete")

   4:                 .Placeholder("Select contry...")

   5:                 .BindTo(new string[] {"Bulgaria","USA","India","Australia","UK"})

   6: )

As you can see I have just bound a simple string array to the auto complete control and this will be the data source now. Here is the output of the above changes:

SNAGHTML22f7d64

The autocomplete control filtered the data source based on what the user has typed and presented only those items which matched the input. We will look at the filtering mechanism in a minute.

Data Binding using DataSource() option:

Another way to provide data to autocomplete control is using the DataSource() method. The DataSource method accepts a read only data source provider. We just need to configure which action method on which controller is responsible to provide the data for the control. Autocomplete will automatically issue an AJAX request to the configured action method and retrieve the data, then bind it to autocomplete. Note that the action method should return a JsonResult as autocomplete will make AJAX request to retrieve the data. Here are the code snippets to achieve this:

Controller Action Method:

   1: public JsonResult GetCountries()

   2: {

   3:     var countries = new string[] { "Bulgaria", "USA", "India", "Australia", "UK" };

   4:     return Json(countries, JsonRequestBehavior.AllowGet);

   5: }

View:

   1: @(

   2:     Html.Kendo().AutoComplete()

   3:                 .Name("kautocomplete")

   4:                 .Placeholder("Select contry...")

   5:                 .DataSource(source  => {

   6:                     source.Read(read =>

   7:                         { read.Action("GetCountries", "Home"); });

   8:                 })

   9: )

As you can see we just set the action method name & the controller name on the data source. Here is how the JSON data looks like at runtime. I have used Developer Tools inside IE to look at the payload. Just press F12 on the page, get to Network tab and start capturing the network traffic:

image

Custom Templates:

AutoComplete also has a flexibility to style the suggestion that is shown by providing your own template. For e.g. in our demo code we have written so far, we have bound the autocomplete to country names. What if we want to show the country flag before the country name when the suggestion is made. Well we can do that by providing an HTML template. We can access the data with a ${data} pattern. Here is the code snippet for providing the custom template:

   1: @(

   2:     Html.Kendo().AutoComplete()

   3:                 .Name("kautocomplete1")

   4:                 .Placeholder("Select contry...")

   5:                 .BindTo(new string[] { "Bulgaria", "USA", "India", "Australia", "UK" })

   6:                 .Template("<span><img src='/Content/Images/${data}.jpg' " +

   7:                             "width='20' height='20' />&nbsp;${data}</span>")

   8: )

Here is the output of the same:
SNAGHTML32a02fd

Filtering the results:

By default the autocomplete filters the suggestions based on a logic “Starts With” i.e. it searches for the items which starts with the user typed text. Autocomplete provides a way to control this filtering by means of Filter() method. The Filter method has 2 overloads – one accepts the string “StartsWith” & “Contains” and another accepts a enum of type FilterType. So here is the code snippet to set the filter type to be “Contains”:

   1: @(

   2:  Html.Kendo().AutoComplete()

   3:                 .Name("kautocomplete1")

   4:                 .Placeholder("Select contry...")

   5:                 .BindTo(new string[] { "Bulgaria", "USA", "India", "Australia", "UK" })

   6:                 .Template("<span><img src='/Content/Images/${data}.jpg' " +

   7:                             "width='20' height='20' />&nbsp;${data}</span>")

   8:                 .Filter(FilterType.Contains)

   9: )

I have the filter logic to be Contains. So here is the output of above code change:

SNAGHTML3371c85

Filtering data on Server:

By default the AutoComplete will do the filtering of items based on user typed text on the client side. This may work fine for small list of data. But if you have very huge list of  data items, this pattern may be a hit on performance because everything needs to be downloaded to the client side and then do the filter. If you ask if there is any better way, well answer is yes and the solution is server side filtering. Instead of filtering the data on the client side, autocomplete control provides a way to send the user typed text to server side. The server side code can then filter the data based on the text passed and return only the matching items. Lets look at the code to achieve this:

For the same of the demo, assume we have a EF context created for Northwind database and we want to list the products in an autocomplete control based on user typed text. We will have a GetProducts action method which accepts a single parameter of type string and lets call it as queryText. Here is the controller action method code snippet:

   1: public JsonResult GetProducts(string text)

   2: {

   3:     var northwind = new NorthwindDataContext();

   4:     var products = northwind.Products.Select(product =>

   5:                                     new ProductViewModel

   6:     {

   7:         ProductID = product.ProductID,

   8:         ProductName = product.ProductName,

   9:         UnitPrice = product.UnitPrice ?? 0,

  10:         UnitsInStock = product.UnitsInStock ?? 0,

  11:         UnitsOnOrder = product.UnitsOnOrder ?? 0,

  12:         Discontinued = product.Discontinued

  13:     });

  14:     if (!string.IsNullOrEmpty(text))

  15:     {

  16:         products = products.Where(p => p.ProductName.Contains(text));

  17:     }

  18:     return Json(products, JsonRequestBehavior.AllowGet);

  19: }

We first instantiate the EF context and get the products. We then check if any text has been passed and if passed, filter the products based on the text and return only the matching list.

Now we will see how to configure the autocomplete to support this. Here is the code snippet for this change:

   1: @(Html.Kendo().AutoComplete()

   2:           .Name("products")

   3:           .DataTextField("ProductName")

   4:           .Filter("contains")

   5:           .DataSource(source => {

   6:               source.Read(read =>

   7:               {

   8:                   read.Action("GetProducts", "Home")

   9:                       .Data("onAdditionalData");

  10:               })

  11:               .ServerFiltering(true);

  12:           })

  13:     )

  14:

  15: <script>

  16: function onAdditionalData()

  17: {

  18:     return {

  19:             text: $("#products").val()

  20:            };

  21: }

  22: </script>

First we have created autocomplete control with name “products”. Then for the read action we have given the action method name and the controller name. One addition to the read method is the Data() method. This in-fact is a hook to the read action of autocomplete and allows us to stick any additional data we want to pass on to the action. Take a look at the action method GetProducts, it has a parameter by name text. We are passing whatever user types as a parameter to the method and get back a filtered list. That’s all there it is to achieve a server side filtering.

Accessing AutoComplete control on the client side:

All Kendo wrappers have a very rich client side API. Using the client side API’s we can access the kendo control on the client side and access a rich set of properties, methods and events. Kendo wrappers are built on the latest and greatest HTML5 standards, so the client side code generated makes use of the new “data-“ (data dash) attributes. We can use the jquery data() method and retrieve them. Here is the code to access a autocomplete control on page load:

   1: var autocomplete = $("#kautocomplete").data("kendoAutoComplete"),

Here “kautocomplete” is the id of the control and we use the jquery data() method to retrieve the kendo control by passing the string “kendoAutoComplete”. This is pretty much a pattern we use to get access to any kendo wrapper from JavaScript.

This comes in handy for instance, when we want to refresh the auto complete on page load. As you saw in the example of data source binding, an AJAX request is issued to get the items the first time a user types in the textbox. What if you want to load the items on page load and keep the autocomplete ready for filtering. This can be done with the following code snippet:

   1: var kac = $("#kautocomplete").data("kendoAutoComplete");

   2: kac.refresh();

You can find the complete list of client side API supported by Kendo AutoComplete widget here.

Summary:

In the first of the many posts to come on Kendo Wrappers for ASP.NET MVC, in this post, we looked at AutoComplete control. We looked at the basics of the using the control and various features like Data Binding, Filtering, Custom Templates and accessing the control from the client side. Hope this excites you to take a dig at the Kendo Wrappers for ASP.NET MVC. Download the free 30 day trial and kick start your kendo adventure.

Till next time – Happy Coding.

image.png

Getting Started Series on Kendo UI Wrappers for ASP.NET MVC

Kendo UI is a flag ship product from Telerik. Kendo UI is everything you need to build super-fast HTML5 web apps. It is a JavaScript UI library and has only one dependency and that is JQuery. With Kendo UI, gone are the days of slow and server heavy web UI page creations. Using Kendo UI you can build web apps in one compact easy-to-use package which includes: UI Widgets, Data Source, Validation and MVVM Framework. As you can see Kendo UI is one package you need and nothing else to cater to your UI needs.

image

Kendo UI doesn’t just stop at being a client side UI framework. If you are one of those many who love server side programming, we do have Kendo UI Server Side Wrappers for ASP.NET MVC development. These wrappers help you produce Awesome HTML5 apps powered by Kendo UI without forcing you to write javaScript. Simply program on the server and the Kendo UI wrappers will handle the HTML and JavsScript.

Here is a example of Kendo UI JavaScript Widgets Vs Kendo UI Server Side Wrappers code:

JavaScript:

   1: <div id="calendar"></div>

   2: <script>
   1:

   2:     $(document).ready(function() {

   3:         // create Calendar from div HTML element

   4:         $("#calendar").kendoCalendar();

   5:     });

</script>

Kendo UI Wrapper for ASP.NET MVC:

   1: @(Html.Kendo().Calendar().Name("kcal"))

As you can see the wrappers makes it easy for you to write code in Razor or ASP.NET syntax and without forcing you to write JavaScript.

So with this blog post we are starting what we call “Getting Started Series on Kendo UI Wrappers for ASP.NET MVC”. Following is the list of blog post that we will be covering in next 4 weeks time. They are:

AutoComplete Wrapper NumericTextBox Wrapper
Calendar Wrapper PanelBar Wrapper
ComboBox Wrapper Slider Wrapper
DatePicker Wrapper Splitter Wrapper
DateTimePicker Wrapper TabStrip Wrapper
DropDownList Wrapper TimePicker Wrapper
Editor Wrapper TreeView Wrapper
Grid Wrapper Upload Wrapper
ListView Wrapper Window Wrapper
Menu Wrapper

As and when the post for individual wrappers are ready we will be updating the above table with the links. So if you are starting on ASP.NET MVC with Kendo UI Wrappers, you may want to book mark this post. This will become an index post for the wrappers.

Hope this series will give you a jump start on using kendo UI Wrappers in ASP.NET MVC development.

Till next – Happy Coding!