Wednesday, 14 November 2012

C# 2012 - Model Binding in Web Forms - CRUD example - Part 1

Watch online -



Here are step-by-step instructions:
1. Create new empty web project
2. Add ADO.NET Entity Data Model

 3. Click Generate from Database


4.
Click New Connection and specify Server Name, Table, etc.

5. I will show my database structure later - it is very simple - only 2 tables.
6. Click OK







7. select Yes, include the sensitive data in the connection string and click Next


8. Select Tables and click Finish
9. Here is my database structure

I have Dpt table that has 0 or more users 
9. Now add Web Form to the project
10. Add gridview to the form - it will display Department ID, Department Name and number of users:
        <asp:GridView ID="GridView1" runat="server" ItemType="WebApplication9.Dpt" AutoGenerateColumns="False" DataKeyNames="DepartmentId"
             AllowPaging="True" AllowSorting="True" PageSize="1" SelectMethod="GetDepartments">
            <Columns>
                <asp:BoundField DataField="DepartmentId" HeaderText="Department Id" SortExpression="DepartmentId" />
                <asp:BoundField DataField="DepartmentName" HeaderText="Department Name" SortExpression="DepartmentName" />
                <asp:TemplateField HeaderText="# of users in department">
                    <ItemTemplate><%#: Item.Users.Count() %></ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

11.  Look at the SelectMethod="GetDepartments"
GetDepartments method will populate grid with departments.
add the following to the code behind:

using System.Data.Entity;
using System.Data.Entity.Infrastructure;

        public IQueryable<Dpt> GetDepartments()
        {
            var query = this.db.Dpts
              .Include(c => c.Users);
            return query;
        }

Run the project - it will display grid with departments and user count - very simple but it shows you few things - how to intellisense is working in model binding and how simple it is to page and sort.
Next I will show you how to add/edit/delete records in the grid.
This is not the nicest blog entry, but if you watch the video - everything should be very straight forward. - i hope

No comments:

Post a Comment