ASP.NET 4.5 Preview
ASP.NET Forms 4.5 Preview introduces us model binding for web forms. Web developers who are familiar with ASP.NET MVC already know what model binding is and how powerful it is. Model binding means framework ability to construct objects of known types using values from presentation layer. In this posting I will show you how to use model binding with ASP.NET Forms 4.5.
That’s enough for preparation work. You can use this method also as static method of Product class.
Let’s define strongly typed Repeater that shows us list of products.
Note the following things:
Sample data
Before going on with examples let’s create some test data too. Let’s define class Product as follows.public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }We need more than one product and to avoid creating database or doing other complex things we define simple method that returns us list of products.
private IListGetProductList() { return new[]{ new Product { Id=1, Name="Heineken", Price=0.88m }, new Product { Id=2, Name="Skopsko", Price=0.97m }, new Product { Id=3, Name="Gambrinus", Price=0.63m }, new Product { Id=4, Name="Lapin Kulta", Price=0.92m }, new Product { Id=5, Name="Rock", Price=1.1m } }; }
That’s enough for preparation work. You can use this method also as static method of Product class.
Strongly typed controls
Previous versions of ASP.NET Forms used reflection on data source objects to read values from objects they were bound to. Web is full of examples about how to bind DataTable toGridView or Repeater and so on. With strongly typed controls ASP.NET Forms makes step closer to object orientation in presentation layer.Let’s define strongly typed Repeater that shows us list of products.
<asp:repeater id="Repeater1" modeltype="WebApplication45.Product" runat="server" selectmethod="GetProducts"> <headertemplate> <itemtemplate> </itemtemplate><footertemplate> </footertemplate><table><tbody> <tr> <th>ID</th> <th>Name</th> <th>Price</th> </tr> <tr> <td><%# Item.Id %></td> <td><%# Item.Name %></td> <td><%# Item.Price %></td> </tr> </tbody></table> </headertemplate></asp:repeater>
Note the following things:
- There is new ModelType property we can use to specify type of data item.
- There is new SelectMethod propertythat specifies the method to call when repeater wants to load data.
- To show data in different templates we can use Item property that is strongly typed and – of course – IntelliSense is also supported. You can see IntelliSense in action on screenshot on right.
Select method
Select method is expected to return us result of type IQueryable<ModelType>. If our data source returns something else we can usually use LINQ extension methods to convert our source data to IQueryable. In our case GetProducts() method is defined as follows.public IQueryableGetProducts() { return GetProductList().AsQueryable(); }
ASP.NET 4.5 Preview
Reviewed by vishal
on
9:12 AM
Rating: