CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Creating Custom Pages in ASP.Net Dynamic Data Website  Submit Articles and Win Geeky Prizes!!   You are not logged in.
Search
 

Product Spotlight
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Creating Custom Pages in ASP.Net Dynamic Data Website

By Satheesh Babu
Posted On Dec 11,2009
Article Rating: (Login)
Be first to rate
this article.
No of Comments: 13
Category: ASP.Net/Dynamic Data Website
Print this article.

Subscribe to our feed!

Creating Custom Pages in ASP.Net Dynamic Data Website

 

Dynamic Data Website is one of the new features released with ASP.Net 3.5 which simplified building data driven website to a greater extent. Read my previous article Introduction to ASP.Net Dynamic Data Websites to start with this new feature.  As i said in my previous article, the Dynamic Data Website provides an infrastructure to perform CRUD operations on the available database objects with predefined templates using LINQ to SQL/LINQ to Entities.

In a real business world, it will not be appropriate to use these default predefined templates and functionalities to achieve our goal. This means, we will require our own customizations done on the Dynamic Data Website for incorporating our business logic to customizing the UI for business branding needs, etc. The good thing about Dynamic Data Website is, it has a greater flexibility to customize it to a very granular level. We can incorporate our business rules wherever required, can change the display of particular database object, fields, etc.

Moving forward, we will see how to build a custom page for a particular database object while the other database objects can still use the default templates. Apart from providing the CRUD operations, we will further customize the page to provide simple search functionality on the database rows.

 

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. Refer the below figure.

Creating Custom Pages in ASP.Net Dynamic Data Website

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.

Creating Custom Pages in ASP.Net Dynamic Data Website

 

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.

Creating Custom Pages in ASP.Net Dynamic Data Website

6.      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 create custom page with search functionality only for Employee object.

 To do this, we need to create a folder inside the DynamicData\CustomPages with the name of the object (by adding “s” at the end) for which we need to create the custom page. In our case, for our employee object create a folder called “Employees”. Now, to make our custom page creation easy, we can copy the list.aspx from “PageTemplates” folder to our Employees folder. We can now start customizing our page.  Refer the below figure to understand better.


Recent Articles

Creating Custom Pages in ASP.Net Dynamic Data Website

Just doing this, the dynamic data website will start using this custom page for employee object alone. You now verify it by executing it. You can do some minor cosmetic modification to understand if the employee object uses the custom page before testing it.  For this, i have added a word “Custom Page:” just before the title of the page (which is table name).

<h2>Custom Page: <%= table.DisplayName%></h2>

 

Execute the page and browse to Employee page. You can see the title as Custom Page: Employees which confirms the dynamic data uses our custom page to render Employee object.

Refer the below output,

Creating Custom Pages in ASP.Net Dynamic Data Website

 

Next, we will go ahead and add search functionality for this page. For easy understanding, we will develop a very basic search page that uses a textbox control and button control to search on the employee name.

 

Drag a TextBox(txtName) control and Button control into our webform.  Configure the LinqDataSource control “WhereParameter” collection to accept txtName as a filter condition on the field name Employee name.

 

Refer the final code below,

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <asp:DynamicDataManager ID="DynamicDataManager1" runat="server" AutoLoadForeignKeys="true" />

 

    <h2>Custom Page: <%= table.DisplayName%></h2>

 

    <asp:ScriptManagerProxy runat="server" ID="ScriptManagerProxy1" />

 

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

        <ContentTemplate>

            <asp:ValidationSummary ID="ValidationSummary1" runat="server" EnableClientScript="true"

                HeaderText="List of validation errors" />

            <asp:DynamicValidator runat="server" ID="GridViewValidator" ControlToValidate="GridView1" Display="None" />

            Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />

            <asp:FilterRepeater ID="FilterRepeater" runat="server">

                <ItemTemplate>

                    <asp:Label runat="server" Text='<%# Eval("DisplayName") %>' AssociatedControlID="DynamicFilter$DropDownList1" />

                    <asp:DynamicFilter runat="server" ID="DynamicFilter" OnSelectedIndexChanged="OnFilterSelectedIndexChanged" />

                </ItemTemplate>

                <FooterTemplate><br /><br /></FooterTemplate>

            </asp:FilterRepeater>

            <asp:Button ID="Button1" runat="server" Text="Search" />

            <asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource"

                AllowPaging="True" AllowSorting="True" CssClass="gridview">

                <Columns>

                    <asp:TemplateField>

                        <ItemTemplate>

                            <asp:HyperLink ID="EditHyperLink" runat="server"

                                NavigateUrl='<%# table.GetActionPath(PageAction.Edit, GetDataItem()) %>'

                            Text="Edit" />&nbsp;<asp:LinkButton ID="DeleteLinkButton" runat="server" CommandName="Delete"

                                CausesValidation="false" Text="Delete"

                                OnClientClick='return confirm("Are you sure you want to delete this item?");'

                            />&nbsp;<asp:HyperLink ID="DetailsHyperLink" runat="server"

                                NavigateUrl='<%# table.GetActionPath(PageAction.Details, GetDataItem()) %>'

                                Text="Details" />

                        </ItemTemplate>

                    </asp:TemplateField>

                </Columns>

 

                <PagerStyle CssClass="footer"/>       

                <PagerTemplate>

                    <asp:GridViewPager runat="server" />

                </PagerTemplate>

                <EmptyDataTemplate>

                    There are currently no items in this table.

                </EmptyDataTemplate>

            </asp:GridView>

 

            <asp:LinqDataSource ID="GridDataSource" runat="server" EnableDelete="true">

                <WhereParameters>

                    <asp:DynamicControlParameter ControlID="FilterRepeater" />

                    <asp:ControlParameter ControlID="txtName" Name="EmployeeName"/>

                </WhereParameters>

            </asp:LinqDataSource>

 

            <br />

 

            <div class="bottomhyperlink">

                <asp:HyperLink ID="InsertHyperLink" runat="server"><img runat="server" src="~/DynamicData/Content/Images/plus.gif" alt="Insert new item" />Insert new item</asp:HyperLink>

            </div>

        </ContentTemplate>

    </asp:UpdatePanel>

</asp:Content>

 

I have bolded the code added by me for search functionality. Execute the application and you can see the search page for the Employee object in action.

Refer the below output.

Creating Custom Pages in ASP.Net Dynamic Data Website

 

Downloads

Download Source 

Conclusion

Thus, with the introduction of Dynamic Data website, it is now the matter of customizing things instead of writing code from scratch to complete a data driven projects. Clearly, Microsoft is working hard to make our work easy and less. Stay tuned, we will see more and more customization we can do on the Dynamic Data Websites in coming days! Download the code attached with this code to see the above example 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
    Custom Field Template Under the Custom Page
    The below links may help you,
    http://www.codedigest.com/Articles/ASPNET/309_Customizing_Fields_in_ASPNet_Dynamic_Data_Website-Part_1.aspx
    http://www.codedigest.com/Articles/ASPNET/312_Customizing_Fields_in_ASPNet_Dynamic_Data_Website-Part_2.aspx
    Custom Field Template Under the Custom Page
    So we know how to customize the List Page for the Employees Table.

    But how do we customize the ForeignKey_Edit FieldTemplate for the Employees Table? I don't want to modify the Insert Page for other tables - only for the Employee table. And I only want it during Insert.

    Thanks!
    Search on Foreign Key
    Hi All!

    I want to able to search on a column that is a foreign key to another table. I don't want to type in the the ID (which is the foreign key). I want to search by Manufacturer name.

    For example you have a Product Table and a Manufacturer Table. On the Product table I wnat to be able to search the Manufacturer Name - not Manufacturer Id. But the Product gridview has ProductID.
    RE:Copy paste does not work
    Paresh,
    Thanks for your comment! Copy and pasting the list.aspx works perfectly..Please check and get back to me the specifc error.
    Copy paste does not work
    Simple copy and paste of list.aspx does not work. I have to change the namespace to make it work.
    search query
    This filter only works with equals to (==) queries, but it does not work like queries (where name like '%john%')
    re: on creating custom pages in ASPNET
    great article i want to use it on my current project.

    thanks
    <a href="http://ignou-student.blogspot.com">http://ignou-student.blogspot.com</a>
    RE:Wow
    Mike,
    Great! you liked it. Yeah, .Net is getting revolutionized these days, its growing securely in every ways so need not panic..Regarding the security of Dynamic data framework in rapid appln development, it is also more secured in every ways. It uses ORM like LINQ to SQL/LINQ to entities that are more secured in data access, which automatically takes care of SQL vulnerabilities like SQL injection, etc..
    Wow
    I am currently a php developer. Some of my clients are looking to move away from their former service providers (who happen to use .net). I have been looking at their stuff for a while and didn't really understand how they were able to put pages up that fast. Now I know! I will be looking into .net more seriously now. I wonder about security sometimes though.
    Re:Creating custom pages in ASPNet dynamic data website
    Great article, i like to use it on my current project.

    rajnish
    <a href="http://ignou-student.blogspot.com">http://ignou-student.blogspot.com</a>
    RE: Expand Search?
    Great... kinda a stupid question(anything can be done with some know how)! But how? :)

    Sorry that is probably a fairly basic thing to do? Very new to programming but this is something I needed to quickly get running to search database before advancing.

    Cheers.
    RE:Expand search?
    Ofcourse you can!
    Expand search?
    Great intro writeup.

    Just wondering if the search can be expanded to search all the fields in the table?

    Cheers,