CODEDIGEST
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Customizing Fields in ASP.Net Dynamic Data Website-Part 1  Submit Articles and Win Geeky Prizes!!   You are not logged in.
Search
 

Sponsors
InstallShield
 

Product Spotlight
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Customizing Fields in ASP.Net Dynamic Data Website - Part 1
Free Trial: InstallShield 2010 for Windows Installers Is InstallShield right for you? InstallShield handles your most complex installation requirements in minutes. Try it now.

By Satheesh Babu
Posted On Jan 08,2010
Article Rating: (Login)
Be first to rate
this article.
No of Comments: 0
Category: ASP.Net/Dynamic Data Website
Print this article.

Subscribe to our feed!

Customizing Fields in ASP.Net Dynamic Data Website - Part 1

 

My previous articles, Introduction to ASP.Net Dynamic Data Websites and Creating Custom Pages in ASP.Net Dynamic Data Website gave a detailed understanding on Dynamic data and creating custom pages. As I said in my previous article, a real business world application requires a lot of customization on basic templates of dynamic data website to achieve our final goal.

In this article, we will see how to customize a field displayed in the Dynamic Data website. The field templates are kept in DynamicData/FieldTemplates folder as user controls in our dynamic data solution. Refer the below figure,

InstallShield

These predefined usercontrols are derived from FieldTemplateUserControl class which provides access to the database fields and their metadata for automatic validations.

The Dynamic data website will use asp.net databound control to present the data in various modes like view, edit and insert. These databound controls will use these usercontrols to render the fields of the database objects in view, edit and insert mode. For example, Boolean field will use Boolean.ascx, DateTime will use DateTime.ascx, etc. The files with “_edit” will be used for insert and editing the fields of corresponding data types. Apart from this, there are 2 more special templates called Children.ascx and ForeignKey.ascx. The Children template is used to display one to many relationships and ForeignKey template will be used to display the foreign key fields (many to one) on the data model. By using these field templates, dynamic data website offers us the flexibility to maintain the display of database fields in centralized location. I.e. if you want to customize a display of a date field across the application then we just need to customize the DateTime.ascx template. Also, by default Dynamic data website does not display primary key field.

 

How the databound controls use the above FieldTemplates?

Dynamic data website includes a customized version of databound controls which will use the above templates for rendering the data. These customized versions of databound controls will in turn use DynamicControl and DynamicField control to use the above field templates.

The databound controls that support template based approach will use DynamicControl to render data fields. i.e. ListView, GridView, FormView and DetailsView control that support template columns will use the DynamicControl to render data to enjoy the flexibility of Dynamic Data like automatic validations, etc.  Something like,

<ItemTemplate>

          <table>

            <tr>

              <td>Name:</td>

              <td>

                <asp:DynamicControl runat="server" DataField="Name" />

              </td>

            </tr>

            <tr>

              <td>Address:</td>

              <td>

                <asp:DynamicControl runat="server" DataField="Address" />

              </td>

            </tr>

<tr>

              <td colspan="2">

                <asp:LinkButton ID="InsertButton" runat="server" CommandName="New" CausesValidation="false" Text="New" />

                <asp:LinkButton ID="EditButton" runat="server" CommandName="Edit" CausesValidation="false" Text="Edit" />

                <asp:LinkButton ID="DeleteButton" runat="server" CommandName="Delete" CausesValidation="false" Text="Delete" />

              </td>

            </tr>

          </table>

</ItemTemplate>

 

Gridview and DetailsView will use DynamicField to render data. Something like,

<Fields>

    <asp:DynamicField DataField="Name" />

    <asp:DynamicField DataField="Address" />

</Fields>

 

Well, we can customize these fields in 2 ways,

1.      Customizing an existing field templates

We might want to customize a particular data type display in our application. For example, the Boolean data type will display CheckBox control in view, edit and insert mode. If our requirement is to display “Yes” or “No” in view mode across the application then we can customize the existing view template for this type which is Boolean.ascx. We will see how to do this in this article.

2.      Adding a new field template

Adding a new template for a data type. For example, if we want to display the Boolean field as “Yes” or “No” for just one object and make the rest of the available objects to use the default template. We will see this in part 2 of this article series.

 

Moving forward, we will customize the default Boolean template to display “Yes” if the field returns true and “No” if the field returns false.

To understand better, we will use the same sample application which we discussed in my previous article.

 

Steps

1.      Open Visual Studio 2008.

2.      Click New> Website and Select “Dynamic Data Web Site”. You can select the language of your choice. I have selected C#. Rename the website name as per your need. The solution will default will have some files created automatically.

3.      Include a new SQL express database inside App_Data folder and create a table called Employees and Department.

Note

You can add database by right clicking App_Data folder in the solution and clicking Add New Item. This will bring a dialog box where you need to select “Sql Server Database” and click Add. Just right click the added database and click “Open” to open your database in Server Explorer on the left pane of your Visual Studio 2008. Then, create a table called Employees and Department with the necessary columns using the “Server Explorer”.

Refer the below figure.

F:\Articles\Dot Net 3.5\Dynamic Data Website\custom pages\SEx.png

 

4.      Next, Design your LINQ to SQL classes that are required for Dynamic Data Website to interact with the database. Right click your project in solution explorer and select “Add New Item..” dialog box. Select LINQ to SQL classes and name it according your need. I have named it as EmployeeDataClasses. Click Add.

5.      Open Server Explorer, Expand the database tables. Drag Employee and Department into LINQ to SQL designer. The LINQ to SQL Objects will be created automatically. Click Save. Refer the below figure.


Useful Books For Developers
Microsoft AJAX Library Essentials: Client-side ASP.NET AJAX 1.0 Explained More books..

Recent Articles

 

F:\Articles\Dot Net 3.5\Dynamic Data Website\custom pages\Domain.png6.      Now, on the solution explorer double click the Global.asax file to open it. On Application_Start event you can see a method called RegisterRoutes() which is defined in Global.asax file. Refer the below code that can be found in Global.asax file for the method.

public static void RegisterRoutes(RouteCollection routes) {

        MetaModel model = new MetaModel();

       

        //                    IMPORTANT: DATA MODEL REGISTRATION

        // Uncomment this line to register LINQ to SQL classes or an ADO.NET Entity Data

        // model for ASP.NET Dynamic Data. Set ScaffoldAllTables = true only if you are sure

        // that you want all tables in the data model to support a scaffold (i.e. templates)

        // view. To control scaffolding for individual tables, create a partial class for

        // the table and apply the [Scaffold(true)] attribute to the partial class.

        // Note: Make sure that you change "YourDataContextType" to the name of the data context

        // class in your application.

        //model.RegisterContext(typeof(YourDataContextType), new ContextConfiguration() { ScaffoldAllTables = false });

 

        // The following statement supports separate-page mode, where the List, Detail, Insert, and

        // Update tasks are performed by using separate pages. To enable this mode, uncomment the following

        // route definition, and comment out the route definitions in the combined-page mode section that follows.

        routes.Add(new DynamicDataRoute("{table}/{action}.aspx") {

            Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),

            Model = model

        });

 

        // The following statements support combined-page mode, where the List, Detail, Insert, and

        // Update tasks are performed by using the same page. To enable this mode, uncomment the

        // following routes and comment out the route definition in the separate-page mode section above.

        //routes.Add(new DynamicDataRoute("{table}/ListDetails.aspx") {

        //    Action = PageAction.List,

        //    ViewName = "ListDetails",

        //    Model = model

        //});

 

        //routes.Add(new DynamicDataRoute("{table}/ListDetails.aspx") {

        //    Action = PageAction.Details,

        //    ViewName = "ListDetails",

        //    Model = model

        //});

    }

To make the development easier and faster, Microsoft have included some codes and description for the method which needs to be configured by us. Just uncomment the first line of code (bolded). Update the “YourDataContextType” on the above code with your data context class, EmployeeDataClasses in my case.

Also, make the property ScaffoldAllTables to true. The final code will be,

 

model.RegisterContext(typeof(EmployeeDataClassesDataContext), new ContextConfiguration() { ScaffoldAllTables = true });

 

Now, we are done with creating a fully operational data driven websites that is capable of doing the CRUD operations on all the available objects in our ORM. Execute the application and see it in action.

 

Next, we will go ahead and customize the Boolean template in the default field templates folder. Browse to DynamicData/FieldTemplates and open Boolean.ascx. Now, comment the CheckBox control in the ascx and add a Literal control. You can see the code where the database value is actually rendered in the CheckBox control in the codebehind of the usercontrol through FieldValue property. Now, assign value as “Yes” if the FieldValue property returns true else “No” to the Literal control. Refer the below code,

 

Boolean.ascx

<%@ Control Language="C#" CodeFile="Boolean.ascx.cs" Inherits="BooleanField" %>

<%--<asp:CheckBox runat="server" ID="CheckBox1" Enabled="false" />--%>

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

 

Boolean.ascx.cs

public partial class BooleanField : System.Web.DynamicData.FieldTemplateUserControl {

    protected override void OnDataBinding(EventArgs e) {

        base.OnDataBinding(e);

 

        object val = FieldValue;

        if (val != null)

        {

            // CheckBox1.Checked = (bool) val;

            Literal1.Text = ((bool)val ? "Yes" : "No");

        }

    }

 

    public override Control DataControl {

        get {

         //   return CheckBox1;

            return Literal1;

        }

    }

}

 

That’s it! Execute the application and you can see Boolean field shows “Yes” or “No” in view mode and CheckBox control in edit and insert mode. Refer the below figure,

In the above figure, IsTemporaryEmployee field is Boolean which uses the customized field template.

Note

Department field uses ForeignKey.ascx template and View Employees in Department object uses Children.ascx as i said earlier.

 

Because we have not customized the edit and insert field template, edit page will still show CheckBox control. Refer below figure,

 

Downloads

Download source

 

Conclusion

Dynamic data website is designed with greater flexibility to customize it for fitting our most of the needs. Thus, this article detailed on customizing the fields in dynamic data. Stay tuned! We will customize more in coming days!

Download the source attached with this article and see it in action.

Happy Coding!!

Similar Articles
  • You can contribute to CodeDigest.Com:
    Donate to CodeDigest.com
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments