Practical4 (II)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

BAIT2113 Web Application Development Chapter 4

Practical 4 (ii) – Model Binding

Section 1: Create A New Model

1.1 Open a new project and name it as BooksPrac.

1. Right click and choose:


2. Click on Visual C# Add -->New Item

3. Select SQL Server


Database

4. Name your database as


BooksInventory.mdf
5. Click Add button

1.2 After you clicked the Add button, you may get this screen. Click Yes.

1.3 Your database is successfully created when you see the


App_Data folder created with BooksInventory.mdf and
BooksInventory_log.mdf created in your Solution Explorer
window.

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

Section 2: Create New Table.

2.1 In the Server Explorer, select Data Connections, and expand the
BooksInventory.mdf database node. Right-clickTables and choose Add New Table.
If yourServer Explorer didn’t show up automatically, you can open the window by
selecting View ➪Server Explorer.

2.2 Enter the column names and data types shown in the following table. Follow the
diagram on how to set the auto increment for the primary key value.
1. Place your cursor on the column
name line. Right click and select
Identity.

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

2. Select the ISBN column and check


its Properties window. Make sure the
Indentity Specification = True,
Identity Increment = 1 and Identity
Seed = 1000. ( Meaning that your
ISBN primary key will be auto started
at 1000 and auto increase by 1 each
line new record being inserted.

3. Save the table with the name


Books by changing [dbo].[Table] to
[dbo].[Books] in the T-SQL tab, and
then click the Update button at the
top-left corner of the table designer.

4. Refresh the database by clicking this icon


in the Server Explorer window.

5. Your table is successfully created


when you can see the Book table
object listed under the Tables node.

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

Section 3: Insert data into table

3.1 Right click the Books table and click on Show Table Data. You will get this screen and
you may insert several data inside.

Section 4: Generate models.

Next, generate the models from the database.

4.1 In solution explorer, right click on Models folder  Add  New Item  ADO.NET Entity
Data Model. You will be presented with the Entity Data Model Wizard.

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

4.2 Leave the connection settings as the following and click next:

4.3 Ensure only Books table is selected with the following settings. Click Finish.

4.4 You will get a security warning – “Running this text template can potentially harm your
computer”. Just click OK.

4.5 The BooksModel.edmx is auto-generated together with a set of classes. Inspect these
classes carefully:
- Book.cs (Book class): This is your model. Read it and understand it before
proceeding.

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

- BooksModel.Context.cs (BooksInventoryEntities class): This is your database


context. Read it and understand it before proceeding.

Also notice that a new connection string was added to the Web.config file. Make sure all
these are there. If not, revise section 4.

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

Section 5: Retrieve and display database records.

5.1 Create a Menu.aspx webform


In the webform, drag and drop the hyperlink server control and change the Text to View
Book List. Set the NavigateUrl properties to ViewBooks.aspx.

~/ViewBooks.aspx

5.2 Create a ViewBooks.aspx webform


Design the page as shown below:

GridView
ID:gvBooks

hyperlink
NavigateUrl:Menu.aspx

5.2.1 View the HTML code for the gvBooks GridView. Then type selectMethod=”. Notice
that as you type this, a <Create New Method> pops out like the figure below. Click on that.

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

5.2.2 Once that is done, view the C# backing code for this webform. You should see a new
method gvBooks_GetData() is created for you automatically. Fill in these codes. It creates
a database context _db and returns the Books collection to be displayed by the GridView.

public IQueryable gvBooks_GetData()


{
BooksInventoryEntities _db = new BooksInventoryEntities();
return _db.Books;
}

5.3 Create a AddBook.aspx webform


Design the page as shown below:

formView
ID: fvBook

button button
text : Create text : Cancel
commandName:Insert commandName:Cancel

Explanation: FormView support add/edit/delete/view record operations. It requires you to


manually write your own templates for each operation. But for now, we are only going to do
an Insert operation.

5.3.1 View your HTML code and add the following code. Just like in the previous GridView
example, as you type the InsertMethod=”, you will see a Create New Method. Click on that
to auto-generate the C# backing code.

<asp:FormView ID="fvBook" runat="server" DefaultMode="Insert"


InsertMethod="fvBook_InsertItem" ItemType="BooksPrac.Models.Book" DataKeyNames="ISBN">
<InsertItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Title"></asp:Label>
<asp:TextBox ID="txtTitle" runat="server" Text='<%# Bind("Title")
%>'></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Author"></asp:Label>
<asp:TextBox ID="txAuthor" runat="server" Text='<%# Bind("Author")
%>'></asp:TextBox>

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

<br />
<asp:Label ID="Label3" runat="server" Text="Price"></asp:Label>
<asp:TextBox ID="txtPrice" runat="server" Text='<%# Bind("Price")
%>'></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Create"
CommandName="Insert" />
<asp:Button ID="Button2" runat="server" Text="Cancel"
CommandName="Cancel" />
</InsertItemTemplate>
</asp:FormView>

Explanation:
- InsertItemTemplate is for in record insertion only.
- The FormView attributes DefaultMode will be set to “Insert” data only since we want
the form to default to Insert record mode.
- The ItemType attribute specifies what is the data model displayed here, so you can
bind Title, Author & Price.
- The DataKeyNames specifies which is the data model’s primary key.
- Button1’s CommandName is set to “Insert” which triggers the InsertMethod when
clicked.
- Button2’s CommandName is set to “Cancel” which triggers a cancel event.
- Take note the CommandNames given are not just any names. They are specific to
the InsertItemTemplate to perform specific function.

NOTE: ItemType must follow whatever namespace you defined for your project’s
Book model. Adjust accordingly.

At this point, if you’re still confused as to what the ASP HTML means, you should refer to
FormView InsertItemTemplate MSDN link.

5.3.2 View the C# backing code. You should see the fvBook_InsertItem() method
already created for you. Type in the following codes.

public void fvBook_InsertItem()


{
Book item = new Book();
TryUpdateModel(item);
if (ModelState.IsValid)
{
// Save changes here
BooksInventoryEntities _db = new BooksInventoryEntities();
_db.Books.Add(item);
_db.SaveChanges();
Response.Redirect("/ViewBooks.aspx");
}
}

Explanation:
- A new instance of Book named item is created.
- TryUpdateModel() will attempt to grab the form inputs and tranfer the data into the
Book item instance.
- ModelState.IsValid checks if the inputs are valid.
- Once checked, the database context _db is called, book added and saved. The user
is then redirected to the ViewBooks.aspx page.

To Learn Programming, You Must Try To Fall in Love with Programming J


BAIT2113 Web Application Development Chapter 4

5.3.3 We now add an ItemCommand action so we can intercept when the Cancel button is
clicked. Double-click on the ItemCommand event as shown.

fvBook events

ItemCommand
Double-click here

5.3.4 A fvBook_ItemCommand method is generated. Type in the following code.

protected void fvBook_ItemCommand(object sender, FormViewCommandEventArgs e)


{
if(e.CommandName == "Cancel")
Response.Redirect("/ViewBooks.aspx");
}

5.3.5 Run your program.

More information on model binding: https://weblogs.asp.net/dwahlin/asp-net-4-5-web-forms-


features-model-binding

Note: Alternatively, you may also choose not to use any Data View Controls. In this case, all
you need is to create your own page with labels, textboxes and button. Then when a Submit
button is clicked, you can can (1) create a model instance, (2) grab the inputs and fill it into
the model instance, and (3) call the database context to add/update/delete the table’s entry
with the model instance.

Exercise to be completed in the lab.


Create 3 more hyperlinks in Menu.aspx page and link it to the page to the page that
will update, delete and show a record count of Books table record. Show it to your
tutor once you complete. You may use the appropriate view controls such as the existing
FormView.

To Learn Programming, You Must Try To Fall in Love with Programming J

You might also like