How to Leverage the .NET 4.5 Model Binding and Strongly Typed Data Controls with Telerik’s ASP.NET AJAX Controls – Part 1

by ASP.NET AJAX Team | Comments 10

The new release of Telerik’s controls for ASP.NET AJAX which we shipped just yesterday includes a ton of great new features and capabilities. This post is the first of two posts in which I will talk about some of the improvements coming with the new RadControls’ suite for the .NET 4.5 framework.  

For the past four months our developers worked hard in order to integrate the .NET 4.5 model binding support into our data bound controls and now you can see the result. The following controls have full ModelBinding support, including selecting data, filtering data, CRUD operations and validation:

The ModelBinding support is a cool extension of the existing data binding model of the ASP.NET. This is the same model binding that was previously only found in ASP.NET MVC, however now it can be found in RadControls for ASP.NET Ajax as well. Together with the ModelBinding feature you can taste the flavor of the new strongly typed data controls implementation into the ASP.NET 4.5.  So let’s see why you should immediately download the new version of our controls and try the new features.

How to do databinding the old and new 4.5 way with RadGrid

If you use any of the data bound controls provided from us, in 99% of all cases there is need of template fields. Till now in order to show the data from a datasource into the template field you you were forced to leverage the late-bound expression by using Eval() or Bind(). For example, below we are using the Eval() helper method to data-bind the "CategoryName" property from an objects which is bound to RadGrid:

<telerik:GridTemplateColumn HeaderText="Category" UniqueName="CategoryID"  DataField="CategoryID" SortExpression="CategoryID">
    <ItemTemplate>
         <%# Eval("Category.CategoryName") %>
    </ItemTemplate>
</telerik:GridTemplateColumn>

When we perform two-way data-binding, we use the Bind() method:

<telerik:GridTemplateColumn HeaderText="Category" UniqueName="CategoryID" DataField="CategoryID" SortExpression="CategoryID">
   <EditItemTemplate>
       <telerik:RadComboBox Skin="Metro" ID="ComboBox1" runat="server" SelectMethod="GetCategories" DataValueField="CategoryID" DataTextField="CategoryName" SelectedValue='<%# Bind("CategoryID") %>'> 
       </telerik:RadComboBox>
    </EditItemTemplate>
</telerik:GridTemplateColumn>

On the other hand, the .NET 4.5 provides ability to enable strongly-typed data templates. To enable them the ItemType property needs to be set on the data bound control. After setting it two new types will be generated in the scope of the control’s template: Item and BindItem. For example the code snippet above could be rewritten as:

<telerik:GridTemplateColumn HeaderText="Category"  UniqueName="CategoryID" DataField="CategoryID" SortExpression="CategoryID">
   <ItemTemplate>
       <%# Item.Category.CategoryName %>
   </ItemTemplate>
   <EditItemTemplate>
         <telerik:RadComboBox Skin="Metro" ID="ComboBox1" runat="server" SelectMethod="GetCategories"  DataValueField="CategoryID" DataTextField="CategoryName" SelectedValue="<%# BindItem.CategoryID %>">
         </telerik:RadComboBox>
  </EditItemTemplate>
</telerik:GridTemplateColumn>

You could use these variables in data-binding expressions and when you want to get full intellisense support.

databinding-expressions

Is this cool? I think it is, but hold on, below I will show you another great feature available in all Rad databound controls for .NET 4.5.

How to Select, Page and Sort Data with Model Binding

To bind the databound RadControls via ModelBinding you need to set only the SelectMethod property to the name of the public method placed into the page's code-behind file:

<telerik:RadGrid ID="RadGrid1" GridLines="None" runat="server" AllowSorting="true" PageSize="10" AllowPaging="True" SelectMethod="GetProducts" AutoGenerateColumns="False">

The GetProducts method has the following declaration:

DataClassesDataContext context = new DataClassesDataContext();
public IQueryable<Employee> GetProducts()
{
    return from e in context.Employees
               select e;
}

Or it can be with parameters:

public IQueryable<Employee> GetProducts(string sortByExpression, int startRowIndex, int maximumRows, out int totalRowCount)
{
    ...
}

In the second signature you have to build a query which sorts and pages the datasource items. 

When we run the page, the data bound controls will call the above method and automatically retrieve the data and render it. The method has to return IEnumerable or IQueryable. Thus users could easily page and sort through the data within our bound controls. The benefits are that our controls will automatically add the appropriate sort and page operators onto an IQueryable<T> query before executing it.

For example, if SelectMethod returns data from Linq DataContext and if the paging of the bound control is turned on, the executed database query will return only items for the current page. If the bound control is sorted by a column, the sorting will also be executed on the database and the sorted result will be returned. That is because the Linq will optimize the query to perform the sort and page operation as part of the database query.

The model binding is a great feature introduced by Microsoft, but still there is some limitation when using it with RadControls. In the following documentation articles you can see current limitations  enclosed into the note paragraphs:

Conclusion

These two features were some of the most frequently requested by you for the past Q. I think that you will be very pleased when you start working with Strongly Typed data bound controls that support ModelBinding and will find that they make your life a lot easier and more comfortable. You can download and try them implemented in all data bound controls.

P.S. Some of you may be guessing that there is something that is missing here and they will be right. This is not the whole story and there will be another blog post coming soon which will uncover the mystery of model binding filtering, CRUD operations and validation.

About the author

Radoslav Kirilov

Radoslav Kirilov

is a software developer at one of Telerik’s ASP.NET AJAX teams. Ever since he joined the company in 2009, he has been working on the data-bound and date-picker controls. His interests are primarily concentrated on ASP.NET, AJAX, MVC, SQL and best practices.

10 Comments

Ben Hayat
Hi Radoslav;

The most widely used control in most application is RadInput. I didn't see this control as one of the supported controls with Model Binding. Can you elaborate if this control already supports the model binding or is it left out?
Basically, any control that accepts data from user needs to have support for model binding. Otherwise, we have to do some the old way and some the new way.

Looking forward to your answer!
Thanks!

..Ben
Telerik MVP
Radoslav Kirilov
Data-bound Web server controls are controls that can be bound to a data source control to make it easy to display and modify data in your Web application. Data-bound Web server controls are composite controls that combine other ASP.NET Web controls, such as Label and TextBox controls, into a single layout. However the RadInput control is not a data bound control, it behaves like extended asp:TextBox. The purpouse of Model databinding introduced in .NET 4.5 is to provide mechanism for giving data to the databound control and this data is the datasource of the control. However the RadInput does not use datasource it operates over one value. The model binding is designed for controls which are working with collections. Also the model binding’s SelectMethod returns strongly typed IQueryable, however the RadInput does not operate over collection and cannot be bound to IQueryable. 

Regards,
Radoslav










Ben Hayat
Hi Radoslav;

So, are you saying that the RadInput, is not compatible with Model Binding mechanism? If yes, what's the suggested solution?

Do we have to deal with RadInput using the older way and using Object Datasource or what's the suggested proposal to move everying to .Net 4.5 Model Binding system?

Thanks!
..Ben
Radoslav Kirilov
Hi Ben, 

The RadInputControl cannot use model binding, because it is not databound control. This is the same as to try using model binding with the asp:TextBox or asp:Label.  The RadInputControl as TextBox works with a single value not with a collection of data. Model data binding is designed to fill data bound controls with data which is collection based (via IQueriable).  In your project you can bind only data bound controls via Model Binding. To all other controls you need to assign values depending on their nature. For example to assign value to the RadTextBox which inherits RadInputControl you just need to set its Text property (like setting Text property of asp:TextBox or asp:Label). 
Additionally a bit more information about where the model binding is “hidden”: 
The SelectMethod which is used for populating control data source is placed into the System.Web.UI.DataBoundControl and all controls which inherits DataBoundControl will work with Model Binding, however the asp:TextBox or asp:Label do not inherit it. The TextBox inherits WebControl which is direct descendant of Control. On the other hand the RadInputControl inherits RadWebControl which is direct descendant of WebControl (like the asp:TextBox). So here we do not have any inheritance from the DataBoundControl, so you cannot use model binding. 
Also the model binding calls SelectMethod via reflection when the page or (control bound via Model Binding) calls its DataBound method. This is the right place for setting data to the data bound control otherwise the data could not be resolved properly and the data bound control will not show it. On the other hand the RadInput control or asp:TextBox (or asp:Label) can receive it value before or after that because they only show a single value which is rendered on the client side, they do not need to resolve the collection objects and extract property value. 
In conclusion you can use Model Binding for all data bound controls on your page and set directly a value to all non-data bound controls. 

Regards,
Radoslav
Ben Hayat
Thank you Radoslav for covering this in detail. I'm sure many others will also benefit from your explanation.

Thank you again!
..Ben
Radoslav Kirilov
Hi Ben,

I want to thank you for your valuable posts here. Also I want to add additional comment: 
You cannot use RadInputControl with model binding because it is not data bound control, however you can include the RadInput controls inside of another data bound control to get the ModelBinding and strongly typed data controls effect: 
<telerik:RadGrid ID="RadGrid1" runat="server" AllowSorting="true" PageSize="10" AllowPaging="True" SelectMethod="GetProducts" AutoGenerateColumns="False">
<telerik:GridTemplateColumn HeaderText="Category"  UniqueName="CategoryID" DataField="CategoryID" SortExpression="CategoryID">
   <ItemTemplate>
       <%# Item.Category.CategoryName %>
   </ItemTemplate>
   <EditItemTemplate>
    <telerik:RadTextBox runat="server" ID="txtFirstName" Text="<%# BindItem.CategoryID %>"></telerik:RadTextBox>
  </EditItemTemplate>
</telerik:GridTemplateColumn>

Regards,
Radoslav
Ben Hayat
Hi Radoslav;

however you can include the RadInput controls inside of another data bound control to get the ModelBinding and strongly typed data controls effect:

You read my mind :-) that was my next question...

In your next blog (part 2) for the CRUD, it would be very helpful to show the RadInput as "Stand alone" and in the "Grid" data bound control, to show the different ways of connecting to data for CRUD.

Thanks for extending your comments!
..Ben
Telerik MVP
Justin
This is pretty neat. Is there a reason why the methods in the code behind for select, update, etc need to be public instead of protected?
Radoslav Kirilov
Hi Justin,

The RadControls ModelBinding mechanism depends on build in ModelBinding mechanism in .NET 4.5. In that context when ModelBinding is used the System.Web.UI.WebControls.ModelDataSourceView object is responsible for finding corresponding method on the Page via reflection. For example if your SelectMethod is “MySelectMehtod” the EvaluateSelectMethodParameters method is called and in some point of it the FindMethod with parameter the name of the SelectMethod. Something like this:
ModelDataSourceMethod modelDataSourceMethod = this.FindMethod(“MySelectMehtod”);.

The FindMethod searches with reflection only for public method on the page because its binding flags are :
.. BindingFlags.Instance | BindingFlags.Public

That’s why if you set your SelectMehtod to be protected the
A public method with the name 'MySelectMethod' was either not found or there were multiple methods with the same name … “ exception will be thrown. 

Regards,
Radoslav
Justin
Ah I see, that makes sense. Thanks. I was trying out using the model binding for a radlistview yesterday. I really like having the added intellisense. 

Comments

  1.    
      
      
       
  2. (optional, emails won't be shown on public pages)
  3. (optional)
Read more articles by ASP.NET AJAX Team - or - read latest articles in Developer Tools