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.
 
Creating Custom Pages in ASP.Net Dynamic Data Website

By Satheesh Babu
Posted On Dec 11,2009
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 16
Category: ASP.Net/Dynamic Data Website
Print this article.

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”. The project will have some aspx and ascx files created automatically by default. 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 using the visual studio's Server Explorer.

Refer the below figure.

Creating Custom Pages in ASP.Net Dynamic Data Website

 

4.      Design your LINQ to SQL classes. Read Introduction to LINQ to SQL – A Beginners Guide if you are new to LINQ to SQL.

Click Save on the LINQ to SQL designer window after creating LINQ to SQL objects. Refer the below figure.

Creating Custom Pages in ASP.Net Dynamic Data Website

6.      Next, open the Global.asax file. You will find a method called RegisterRoutes() in Application_Start event. 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

        //});

    }

 

Update the “YourDataContextType” in the above auto generated code with your data context class( EmployeeDataClasses in my case) as said in the code comments.

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

 

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

 

Save the file and execute the application to see the basic CRUD operations on the datamodel 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.


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 CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
What a great <a href
What a great <a href="http://jjqmzbxtfxk.com">resuroce</a> this text is.
Canillg all cars, ca
Canillg all cars, calling all cars, we're ready to make a deal.
Thx
Thank you very much for this article.
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,