0% found this document useful (0 votes)
17 views22 pages

09 - More MVC

The document outlines the requirements and feedback for Practical 07 and 08 of a Model-View-Controller (MVC) web application course. It includes instructions for updating web pages, creating models and controllers, managing databases using Entity Framework, and implementing CRUD operations. Additionally, it provides guidance on validation, navigation updates, and submission procedures for the practical assignments.

Uploaded by

nygracka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views22 pages

09 - More MVC

The document outlines the requirements and feedback for Practical 07 and 08 of a Model-View-Controller (MVC) web application course. It includes instructions for updating web pages, creating models and controllers, managing databases using Entity Framework, and implementing CRUD operations. Additionally, it provides guidance on validation, navigation updates, and submission procedures for the practical assignments.

Uploaded by

nygracka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

2024/10/04

Model-View-Controller Web Applications

Lecturer:
Ms Marinda Taljaard

Admin
▪Busy with marking – you will get feedback as soon as possible
• Remainder of prac 5
• Prac 6
• Prac 7 – marks already sent, updated marks will be sent with the next set of marks
• Semester test

1
2024/10/04

Practical 07 requirements
▪ Topic:
Your favourite Book Series / Streaming Service Series / Movie Series
▪ Update the Welcome and Privacy pages as follows:
• Welcome page: add some information about the topic you chose (e.g. info about Lord of the Rings
trilogy)
• Privacy page: Add your personal details (name, surname, student number and an image)
▪ Add a Model (instructions in tutorial)
▪ Add the Controller with the CRUD views – Create, Read, Update, Delete (instructions in
tutorial, make use of entity framework)
▪ Create the database table (instructions in tutorial) – table must have at least 4 fields
▪ Edit main navigation option text – add an option to the Index page of the new
controller
▪ Attempt to override some aspect of the css formatting – e.g. different background
colour

Prac 07 feedback
▪Marked / 20
• PDF file / 2
• Model & Database / 6
• Home Controller / 4 (Updating Index and Privacy Views)
• Movies Controller / 4
• Navigation / 2
• Formatting / 2

2
2024/10/04

Prac 07 feedback
▪Addingthe image to the privacy page resulted in some
pages with a broken image link
• Image cannot be found using the URL path provided
▪Preferred solution
• Addan images folder to the wwwroot folder, upload your
image(s) there, then use a URL path similar to:
•<img src=“~/images/picture.jpg” />

▪Navigation not updated, or not working


• Wrong controller/method name

Model – View - Controller


▪Controller
• Containscode for creating methods to access the data
and direct the user to the appropriate view
▪Model
• Contains context class
• Contains a class for each database table

▪View
• Contains instructions on what the user should see

3
2024/10/04

Creating the Database


▪EntityFramework – Code-First approach
▪EF API will create the database based on your classes and configuration
• Add Model(s)
• Add Controller
• Run EF commands in Package Manager Console

Closer look at the Model


▪ Each aspect from the domain needs a class
• E.g.
a movie application that also handles rentals and customers, or
• A movie application that should also be used for other favourites
• Most probably different database tables and therefor also different classes for movie data,
book data and series data
▪ UsingEntity Framework will
create the required aspects
• ApplicationDbContext
- See this as your database
connection
• DbSet
- See this as your link to the table

4
2024/10/04

Adding a model & controller to your application


▪If a new table is required in your database
• In addition to what was created before
▪Add a new model to the Models folder
• Specify the attributes
• Create the empty constructor

▪Add a controller for the new model


• MVC Controller with views, using
Entity Framework

Creating the corresponding database table


▪Return to the Package Manager Console to
▪Use Add-Migration command to create the code
required to create the database table
•PM> Add-Migration NewTableBook
▪Use Update-Database command to create the table
•PM> Update-Database

5
2024/10/04

Viewing the tables


▪Open the SQL Server Object
Explorer panel
▪Expand enough to find your tables
▪Take note of the following:
• IDENTITY(1,1)
• NOT NULL

Some database concepts


▪Code First primary key convention:
• Property with name Id or {class name}+”Id” will act as the primary key for that entity
• Can also be specified in object class with Data Annotation [Key]

▪Relationships
▪ https://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-
code-first.aspx

6
2024/10/04

Running the application


▪ No navigation option yet – so URL can be edited to read …../Books
▪ The controller will take you to the Index view of the Books controller
• Records can be added using the Create View
• Take note of the required field message

Closer look at the Model


▪ Annotations can be added in the class file
 Also referred to as decoration
 [Required] – error message can
be specified

7
2024/10/04

Values required or not?


▪When table was created – fields were
specified as NOT NULL (cannot be
empty)
▪This can be changed in the migration
code generated, but we are not
looking into that today

Update the navigation


▪Remember to update the
master page (_Layout.cshtml)
to add a navigation option

8
2024/10/04

Model-View-Controller
▪ Each aspect from the domain needs its own database table
▪ Every database table will need its own controller – to provide the
functionality of the CRUD operations
▪ Every controller need a corresponding folder within the Views
folder where the specific files can be found, e.g.
• Model, Controller, Views to handle CRUD operations for movie
data
• Model, Controller, Views to handle CRUD operations for book
data
• Model, Controller, Views to handle CRUD operations for series
data

Examining a generated view


▪ Uses razor syntax
• View engine supported in ASP.NET Core MVC
▪ Allows a mix of HTML and server side code
using C#
• Files has .cshtml extension
▪ Startwith @ symbol to write server side C#
code with html code
• @model allows use of model object anywhere in the
view
• @Html.DisplayNameFor()
• @Html.DisplayFor()

9
2024/10/04

HTMLHelper Class
▪ Renders html controls in the razor view, e.g.
• Binds the model object to HTML controls to display value of
model properties
• Assigns the value of the controls to the model properties
while submitting a web form
▪ @Html.DisplayNameFor(…) gets the
display name for the model
▪ @Html.DisplayFor(…) generates a html
string based on the value of the model property

Passing data between components


▪ Using ViewData
• Transfersdata from controller to view, or
• Between views
• E.g. ViewData[“Title”] getting a value in the View – then used in _Layout
file

10
2024/10/04

Strongly typed models


▪ Type of object is known and available
▪ Better compile time checking
▪ Scaffolding mechanism in VS uses this approach
when using the templates (creating methods and
views)
▪ @model Keyword
• Used at the top of a View
• Specifies the type of object the view expects

A closer look at the Details method


▪ Find the relevant record
• Display view with information of that record
▪ Some checking provided
▪ var book = await _context.Book
▪ .FirstOrDefaultAsync(m => m.ID == id);
▪ Await – multiple active operations on the same context instance are not supported – use
await to ensure that any asynchronous operations have completed before calling another
method on this context
▪ (m => m.ID == id)
▪ Lambda expression: Book m where the ID of m
equals the id received from the calling method

11
2024/10/04

A closer look at the Edit method


▪ Consider the goal that a record must be updated
▪ User views items, selects to edit item
• Controller must find the selected item details
• Display item in editing mode
▪ User
makes changes to item, selects to save the
changes
• Controller needs to save changes
▪ Notethat the Edit method are actually
overloaded:
• There are 2 Edit methods in the Controller – Get and
Post

A closer look at the Edit method


▪Get:
• Find the relevant record in the table
• Display view with that record
• Some error checking

12
2024/10/04

A closer look at the Edit method

▪Post:
• Some error checking
• Save to table
• Return to Index view

HTTP GET and HTTP POST


▪HTTP GET
• When action method is called by a request URL (by browser)
• E.g. Display the details of the record that was selected

▪HTTP POST
• When action method is called by something like button click event
• E.g. Save the updated information back to the database
• [HttpPost] required to specify that the second method can only be invoked for POST
requests

13
2024/10/04

A closer look at the Delete Method


▪ Get:
• Find the relevant record in the table
• Display view with that record

A closer look at the Delete Method


▪ Post:
• Find the relevant record in the table
• Use the Remove method
• Save the changes

14
2024/10/04

A closer look at the Delete Method


▪ Delete Method is overloaded, but the parameter signatures are the same – which may
not be
▪ To solve the issue the POST method is named DeleteConfirmed
• But the way MVC works is that the Get and Post methods must have the same name
• ActionName(“Delete”) fixes the MVC routing issue

Validation attributes
▪ [Required]
▪ [RegularExpression]
▪ [Range]
▪ [Compare]

15
2024/10/04

Validation
▪ Look for corresponding code in
View
• E.g.
relevant when creating new
records

Consider DB options
▪With Web Forms you had an Access file that you could access from outside
the application
▪Using the EF functionality, the database is created within VS, and available
on your local machine
• This is a problem for handing in your project to be evaluated on another PC
• It is possible to specify initial “seed” data for database tables, which can then be run
from the Package Manager Console

16
2024/10/04

Providing initial data to database tables


▪Update the ApplicationDbContext.cs file to include some initial
data
▪Execute commands using Package Manager Console
•Add-migration “provideMigrationName”
•Update-database

Providing initial data to database tables


▪ Add new records to a specified table as follows:

17
2024/10/04

Specify object properties


▪ Builder.Entity<Book>().HasData()

Add migration
▪ Using Package Manager Console

18
2024/10/04

Possible error message


▪Execute commands using Package Manager Console
•Add-migration “provideMigrationName”
•Update-database

▪Ifpackage manager displays an error message about the Identity entities,


the following statements might solve the issue
• Update ApplicatioDbContext.cs file

Running the application again

19
2024/10/04

Practical 08
▪ Start a new ASP.NET Core MVC project for Prac 8
• Include Individual user accounts
▪ Topic: Delivery Guy Web Application
• Tables for Area, Driver and Package (refer to the Access database on Moodle for guidance)
▪ Usingthe template application, you should have a working application from the start
▪ Keep the Home Controller and Index View
• Update the Index View
- Remove the current information, add some paragraphs about the Courier Guy Company,
add the image
• Remove the Privacy View
- Implying removing ALL traces of the privacy view

Practical 08
▪ Create an object class for each of the required database tables – you can use the
same fields as in the Access database
• This should result in a different table for each object class
▪ Create a controller with corresponding views for each of the model object classes
• All
CRUD (create, read, update, delete) functionality must be available for the Area, Driver and
Package tables
▪ Add at least 3 records to each of your database tables
• Using the method of providing the data in the ApplicationDbContext.cs file

20
2024/10/04

Practical 08
▪ Update the main navigation bar:
• Display a suitable application name on the left
• Ensure that your main navigation contains options for your user to access to each of
the tables in the database
▪ Add your details in the footer of the web application

▪ Change some aspect of the formatting provided by the bootstrap instructions

Practical 08 pdf file


▪ Create
a word document to show that your web application runs,
and what the pages looks like in the browser
• Create a heading for each page in your web application
▪ View all the pages in your web application in the browser
▪ Make images/screenshots of each of the pages (you can use a tool
like the Snipping tool)
• Paste the image for each page under the relevant heading

▪ Save the word document as a pdf document in the root (top level
folder) of your web application

21
2024/10/04

Practical 08
▪When you are ready to submit:
• Click
on Build, Clean Solution
• Compress this version, and upload the compressed folder to Moodle

▪Due on Wednesday 9 October, 12:00 midday

More specific Resources


▪HTTP GET and HTTP POST
• https://www.c-sharpcorner.com/UploadFile/3d39b4/getting-data-from-view-to-
controller-in-mvc/
▪Code-First conventions
• https://www.entityframeworktutorial.net/code-first/code-first-conventions.aspx
▪Data Annotation Attributes
• https://www.entityframeworktutorial.net/code-first/key-dataannotations-attribute-in-
code-first.aspx
▪Validation:
• https://learn.microsoft.com/en-
us/aspnet/core/mvc/models/validation?view=aspnetcore-7.0

22

You might also like