CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

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

By Satheesh Babu
Posted On Jan 08,2010
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 4
Category: ASP.Net/Dynamic Data Website
Print this article.

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,

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 from your Start menu.

2.      Click New> Website and Select “Dynamic Data Web Site”. I have selected C# as the language. The solution by 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.

Refer the below figure.

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

 

4.      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 to your choice. 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.




 

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

6.      Find the RegisterRoutes() method in Application_Start event of your Global.asax file. You will find the below code for RegisterRoutes() method in Global.asax file.

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

        //});

    }

Just uncomment the first line of code (bolded) and configure your data context class name in the place of “YourDataContextType” on the above code, EmployeeDataClasses in my case.

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

 

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

 

This completes the creation of fully operational CRUD website on our data model. 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 CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
.net dynamic fields
very nice explanation but can get more easy by other way
U can use this code:
public class ServiceFactory
{
internal static ProductCatalogueDataContext CreateDataContext()
{
string connectionstring = ConfigurationManager.ConnectionStrings["ProductCatalogueDataContext"].ConnectionString;
return new DataContextFactory().CreateDataContext(connectionstring);
}
}
DataContext
Hi All!

Has someone tried to modify the mappingSource of the DataContext at run-time before anything is excecuted. I want to able to change the datasource at run-time to point at different databases depending on who the User is.

Right now it is using this code:

base(global::System.Configuration.ConfigurationManager.ConnectionStrings["FAMP_ConnectionString"].ConnectionString, mappingSource)


Thanks!
Thanks
Thanks... Nice explanation ...