Sunday, May 29, 2011

ASP.NET Dynamic Data - Part 4 - Customize Entity Templates

The next topic in my series on ASP.NET Dynamic Data, I'll focus on how to customize the table layout using entity templates. I'll continue to work on my project described in part 3. The only thing changed from part 3 is instead of the custom field template which changed the background color, based on the stock count, now changes for foreground color instead.
At the moment the Web Site uses the default details table layout, which looks like this:
This is a very basic template, are a very often not what you need. In this case I would like something different, something like this:

I'm not a designer so no fancy colors or anything here, but this could be added easily.

Create the custom entity template

First we need to create the custom entity template, this template will be used for all entities in the Products table. We need to Add New Item, on the /DynamicData/EntityTemplates folder and choose the Web User Control item, the name of the control must be the same as the data model entity that represents the table, in my case it must be Products.ascx.
The markup for the new table contents are easily added, and could look like this:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Products.ascx.cs" Inherits="DynamicData_EntityTemplates_Products" %>
<tr>
    <td class="DDLightHeader" colspan="4">Producy Entry</td>
</tr>
<tr>
 <td class="DDLightHeader">Id:</td>
 <td>
        <asp:DynamicControl runat="server" DataField="Id" />
    </td>
 <td class="DDLightHeader">Name:</td>
 <td>
        <asp:DynamicControl ID="DynamicControl1" runat="server" DataField="Name" />
    </td>
</tr>
<tr>
 <td class="DDLightHeader">Stock:</td>
 <td>
        <asp:DynamicControl ID="DynamicControl2" runat="server" DataField="Stock" />
    </td>
 <td class="DDLightHeader">Price:</td>
 <td>
        <asp:DynamicControl ID="DynamicControl3" runat="server" DataField="Price" />
    </td>
</tr>
<tr>
 <td class="DDLightHeader" colspan="4">Description:</td>
</tr>
<tr>
 <td colspan="4">
        <asp:DynamicControl ID="DynamicControl4" runat="server" DataField="Description" />
    </td>
</tr>
After the markup are written, you need to change to base class from UserControl to EntityTemplateUserControl, this is done in the usercontrol's code-behind file. The code looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.DynamicData;

public partial class DynamicData_EntityTemplates_Products : EntityTemplateUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Test the Web Site

This is all that needs to be done in order to create a custom entity template, easy right? When the Web Site is tested in looks like this:

No comments:

Post a Comment