CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Customizing Fields in ASP.Net Dynamic Data Website-Part 2   You are not logged in.
Search
 

Technologies
 

Sponsors
 

CodeDigest Navigation
 

Technology News
 

Community News
No News Feeds available at this time.
 
Customizing Fields in ASP.Net Dynamic Data Website - Part 2

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

Subscribe to our feed!

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

 

Re-Cap

Dynamic data website is a new feature released with ASP.Net 3.5. This new feature allows us to develop a fully operational data driven websites very easily.

Read the following articles to know more,

Introduction to ASP.Net Dynamic Data Websites

Creating Custom Pages in ASP.Net Dynamic Data Website

 

We have started an article series “Customizing Fields in ASP.Net Dynamic Data Website” to customize the fields displayed in ASP.Net Dynamic data website.

 

In part 1 of this article series, we have seen how to customize an existing field template. We will continue the article series with part 2 to include a new field template for a datatype that can be used only at specific places. For example, if we want to display the Boolean field as “Yes” or “No” at some specific places and make the rest of the website to use the default template that uses CheckBox control to display the Boolean field.

 

To have an easy understanding, we will use the same data model we used in my previous articles. We already have a Boolean field called IsTemporaryEmployee in Employee table. Apart from this, we will include one more new Boolean field in Employee table called HasPassport to understand this article. Moving forward, we will include a new field template and configure it so that the new Boolean field template is used for HasPassport field while the other Boolean field still uses the default.

Something like below,

 

Steps

1.      Open Visual Studio 2008.

2.      Click New> Website and Select “Dynamic Data Web Site”. You can select the language of your choice, rename the project name and click OK. The solution will have some files created automatically by default.

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

Note

Use "Server Explorer" in Visual Studio to do this easily. Right click your new Database in App_Data folder and select Open to view your database in Server Explorer. Now, create a table called Employees and Department with the necessary columns.

 

Refer the below figure.

 

4.      Design your LINQ to SQL classes. Refer Part 1 to know more. I have named my Data Context class 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.

6.      On Application_Start event of your Global.asax file, you can see a method called RegisterRoutes() which is defined in Global.asax file. Refer the below code.

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

        //});

    }

In the above auto generated code, 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 });

 

That's it! We are noew done with creating a fully operational data driven websites that is capable of doing the CRUD operations on our data model. Execute the application and see it in action.

 

Next, we will go ahead and add a new field template for Boolean field in the default field templates folder. Browse to DynamicData/FieldTemplates and right click FieldTemplates folder and select “Add New Item..”.  Select “Dynamic DataField” from the dialog box and specify a name for your new field template, i have given as “BooleanYN.ascx”.

Refer the below figure,

 

 

 



ASP.Net Hosting

Recent Articles

This will add a new user control with name “BooleanYN.ascx” for view and “BooleanYN_Edit.ascx” for edit/insert mode.  For time being, we will exclude the edit template and will finish configuring the view template first.  Refer below,

 

As is said in my previous articles, the code behind of this new template will be inherited from System.Web.DynamicData.FieldTemplateUserControl class. This class will provide the access to the field value and meta data for automatic validations, etc.

Also, Dynamic data framework will automatically place a Literal control for view mode(See ascx file).

Now, from the codebehind file, assign value as “Yes” if the FieldValue property returns true else “No” to the Literal control.

Refer the below code,

 

BooleanYN.ascx

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

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

BooleanYN.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)

        {

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

        }

    }

 

    public override Control DataControl {

        get {

            return Literal1;

        }

    }

}

 

Next, we have to configure the Employee object to use the new field template for HasPassport field.

 

Dynamic data website includes a property called UIHint that helps us to do this. We need to create a meta data class for the employee object and decorate the HasPassport field with UIHint attribute. The UIHint attribute will take a string parameter that represents the new field template name and uses the field template to render the field specifed.

Now, this meta data class should be exposed with the Employee object to look for the additional meta data in order to render the fields. This can be done by decorating the Employee object with a property called MetadataType.

To do this, include a new class file into your project called Employee.cs. Make the class as partial as we already have an Employee object in our data model.  Define a meta data class called EmployeeMetadata where we can specify the HasPassport field to use the new template. Decorate the Employee partial class with MetadataType property.

Note

We can include MetadataType directly in your Employee class in designer.cs file, but whenever you make any changes to your datamodel the changes will be cleared off and requires re-configuring. Hence, creating a partial class and decorating it with this property will help us to prevent this issue.

 

Refer the below code,

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.DynamicData;

using System.ComponentModel.DataAnnotations;

 

/// <summary>

/// Summary description for Employee

/// </summary>

 

[MetadataType(typeof(EmployeeMetadata))]

public partial class Employee

{

      

}

public class EmployeeMetadata

{

    [UIHint("BooleanYN")]

    public System.Nullable<bool> HasPassport; 

  

}

 

That’s it! Execute the application and you can see Boolean field shows “Yes” or “No” in view mode for the HasPassport field and displays CheckBox control for IsTemporaryEmployee field. Refer the figure above [First Image of the article]. Edit and Insert mode will still show CheckBox control as we have excluded the new edit template for both the fields.

 

Now, we will go ahead and include the edit template which we excluded when adding new field template and customize it. The default template will include textbox control and validators to validate. Remove all these and include a RadioButton control, just to differentiate it from default Boolean edit template which includes CheckBox control. Override the OnDataBind method to populate the RadioButton control in edit mode.

Note

Easy way to customize is to copy the content of default Boolean edit template and start customizing it. Copy paste the ascx and codebehind from an existing Boolean template and start customizing it.

 

Refer the code below,

ASCX

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="BooleanYN_Edit.ascx.cs" Inherits="DynamicData_FieldTemplates_BooleanYN_EditField" %>

 

<asp:RadioButton ID="RadioButton1"  runat="server" />

 

Note

I have deleted unwanted code ascx.

 

ASCX.CS

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

    protected void Page_Load(object sender, EventArgs e) {

        //TextBox1.MaxLength = Column.MaxLength;

        //if (Column.MaxLength < 20)

        //    TextBox1.Columns = Column.MaxLength;

        //TextBox1.ToolTip = Column.Description;

 

 

       // SetUpValidator(RequiredFieldValidator1);

        //SetUpValidator(RegularExpressionValidator1);

        //SetUpValidator(DynamicValidator1);

      

    }

 

    protected override void OnDataBinding(EventArgs e)

    {

        base.OnDataBinding(e);

 

        object val = FieldValue;

        if (val != null)

            RadioButton1.Checked = (bool)val;

    }

 

    protected override void ExtractValues(IOrderedDictionary dictionary) {

       // dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);

        dictionary[Column.Name] = RadioButton1.Checked;

    }

 

    public override Control DataControl {

        get {

           // return TextBox1;

            return RadioButton1;

        }

    }

}

Execute the application and you can see RadioButton control in edit page. 

Refer the below figure.

 

Downloads

Download Source

 

Conclusion

As i said in this article series, dynamic data website offers a greater flexibility to customize it for fitting our most of the needs. Part 1 and Part 2 of this article series would have given you a very basic idea on customizing the dynamic data website.

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:
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments
    How to create RadioButtonList
    Hi Satish,
    I have created RadioButton sample by reading your article, it was good. I dont know much about DynamicData. i didnt find any tutorials where i can learn more about dynamic data [ custom page development and new DataFieldTemplate] like generating RadioButtonList, ListBox and etc., now i am trying to create RadioButtonList by copying ForeignKey.ascx file but not got any success. can you tell me how to generate radiobuttonlist.
    Multiple radiobutton
    I tried this sample in VS2010 its not worked when i tried in VS2008 its working fine. Any modification has to do in 2010?

    Another Question is, I want to display RadioButtonList instead of Combobox, how to do that?