text01
text01
Prerequisite
Visual Studio Code
The first command creates a new project called MvcMovie and create a folder with the
same name containing the project files.
When Visual Studio Code requests that you add assets to build and debug the project,
select Yes. If Visual Studio Code doesn't offer to add build and debug assets,
select View > Command Pale e and type ".NET" into the search box. From the list of
commands, select the .NET: Generate Assets for Build and Debug command.
Visual Studio Code adds a .vscode folder with generated launch.json and tasks.json files.
select Yes if you see a dialogue box asking to trust the cer ficate
In Visual Studio Code, press Ctrl+F5 to run the app without debugging.
Launching the app without debugging by selec ng Ctrl+F5 allows you to:
In Visual Studio Code, from the Run menu, select Stop Debugging or press Shi +F5 to stop
the app
Add a controller:
Select the EXPLORER icon and then right-click Controllers > New File and name the new
file HelloWorldController.cs
Replace the contents of Controllers/HelloWorldController.cs with the following code:
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace MvcMovie.Controllers;
An HTTP endpoint:
Is a targetable URL in the web applica on, such as h ps://localhost:5001/HelloWorld.
Combines:
o The network loca on of the web server, including the TCP port: localhost:5001.
The first comment states this is an HTTP GET method that's invoked by
appending /HelloWorld/ to the base URL.
Append /HelloWorld to the path in the address bar. The Index method returns a string
MVC invokes controller classes, and the ac on methods within them, depending on the
incoming URL. The default URL rou ng logic used by MVC, uses a format like this to determine
what code to invoke:
/[Controller]/[ActionName]/[Parameters]
o The second part of the URL segment determines the ac on method on the class.
So, localhost:5001/HelloWorld/Index causes the Index method of
the HelloWorldController class to run. No ce that you only had to browse
to localhost:5001/HelloWorld and the Index method was called by default. Index is the
default method that will be called on a controller if a method name isn't explicitly
specified.
o The third part of the URL segment (id) is for route data.
The Welcome method runs and returns the string “This is the Welcome ac on method....” For
this URL, the controller is HelloWorld and Welcome is the ac on method. You haven't used
the [Parameters] part of the URL yet.
Now we want to modify the code to pass some parameter informa on from the URL to the
controller. For example, /HelloWorld/Welcome?name=Rick&num mes=4.
Change the Welcome method to include two parameters as shown in the following code.
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace MvcMovie.Controllers;
h ps://localhost:{PORT}/HelloWorld/Welcome?name=Rick&num mes=4
The name and numTimes parameters are passed in the query string.
The ? (ques on mark) in the above URL is a separator, and the query string follows.
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace MvcMovie.Controllers;
The third URL segment matched the route parameter id as defined in the rou ng
template in the Program.cs file.
The Welcome method contains a parameter id that matched the URL template in
the MapControllerRoute method.
Currently the Index method returns a string with a message in the controller class.
In the HelloWorldController class, replace the Index method with the following code:
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace MvcMovie.Controllers;
Controller methods:
Replace the contents of the Views/HelloWorld/Index.cshtml Razor view file with the following:
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
Navigate to h ps://localhost:{PORT}/HelloWorld:
The Index method in the HelloWorldController ran the statement return View();, which
specified that the method should use a view template file to render a response to the
browser.
A view template file name wasn't specified, so MVC defaulted to using the default view
file. When the view file name isn't specified, the default view is returned. The default
view has the same name as the ac on method, Index in this example. The view
template /Views/HelloWorld/Index.cshtml is used.
The following image shows the string "Hello from our View Template!" hard-coded in the
view:
Select the menu links MvcMovie, Home, and Privacy. Each page shows the same menu layout.
The menu layout is implemented in the Views/Shared/_Layout.cshtml file.
Applying the HTML container layout across mul ple pages in the site.
Find the @RenderBody() line. RenderBody is a placeholder where all the view-specific pages
you create show up, wrapped in the layout page. For example, if you select the Privacy link,
the Views/Home/Privacy.cshtml view is rendered inside the RenderBody method.
Change the tle, footer, and menu link in the layout file
Replace the content of the Views/Shared/_Layout.cshtml file with the following markup.
The changes are highlighted:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Movie App</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/MvcMovie.styles.css" asp-append-version="true"
/>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-
white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Movies" asp-
action="Index">Movie App</a>
<button class="navbar-toggler" type="button" data-bs-
toggle="collapse" data-bs-target=".navbar-collapse" aria-
controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-
content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-
controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-
controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
In the preceding markup, the asp-area=""anchor Tag Helper a ribute and a ribute value was
omi ed because this app isn't using Areas.
Note: The Movies controller hasn't been implemented. At this point, the Movie App link isn't
func onal.
Save the changes and select the Privacy link. No ce how the tle on the browser tab
displays Privacy Policy - Movie App instead of Privacy Policy - MvcMovie
Select the Home link.
No ce that the tle and anchor text display Movie App. The changes were made once in the
layout template and all pages on the site reflect the new link text and new tle.
@{
ViewData["Title"] = "Movie List";
}
The tle and <h2> element are slightly different so it's clear which part of the code changes the
display.
ViewData["Title"] = "Movie List"; in the code above sets the Title property of
the ViewData dic onary to "Movie List". The Title property is used in the < tle> HTML element
in the layout page:
Browser tle.
Primary heading.
Secondary headings.
If there are no changes in the browser, it could be cached content that is being viewed. Press
Ctrl+F5 in the browser to force the response from the server to be loaded. The browser tle is
created with ViewData["Title"] we set in the Index.cshtml view template and the addi onal "-
Movie App" added in the layout file.
Controller ac ons are invoked in response to an incoming URL request. A controller class is
where the code is wri en that handles the incoming browser requests. The controller retrieves
data from a data source and decides what type of response to send back to the browser. View
templates can be used from a controller to generate and format an HTML response to the
browser.
Controllers are responsible for providing the data required in order for a view template to
render a response.
Do business logic
A view template should work only with the data that's provided to it by the controller.
Maintaining this "separa on of concerns" helps keep the code:
Clean.
Testable.
Maintainable.
Currently, the Welcome method in the HelloWorldController class takes a name and
an ID parameter and then outputs the values directly to the browser.
Rather than have the controller render this response as a string, change the controller to use a
view template instead. The view template generates a dynamic response, which means that
appropriate data must be passed from the controller to the view to generate the response. Do
this by having the controller put the dynamic data (parameters) that the view template needs in
a ViewData dic onary. The view template can then access the dynamic data.
The ViewData dic onary is a dynamic object, which means any type can be used.
The ViewData object has no defined proper es un l something is added. The MVC model
binding system automa cally maps the named parameters name and numTimes from the query
string to parameters in the method. The complete HelloWorldController:
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace MvcMovie.Controllers;
The ViewData dic onary object contains data that will be passed to the view.
You'll create a loop in the Welcome.cshtml view template that displays "Hello" NumTimes.
Replace the contents of Views/HelloWorld/Welcome.cshtml with the following:
@{
ViewData["Title"] = "Welcome";
}
<h2>Welcome</h2>
<ul>
@for (int i = 0; i < (int)ViewData["NumTimes"]!; i++)
{
<li>@ViewData["Message"]</li>
}
</ul>
h ps://localhost:{PORT}/HelloWorld/Welcome?name=Rick&num mes=4
Data is taken from the URL and passed to the controller using the MVC model binder. The
controller packages the data into a ViewData dic onary and passes that object to the view. The
view then renders the data as HTML to the browser.
In the preceding sample, the ViewData dic onary was used to pass data from the controller to a
view. Later in the tutorial, a view model is used to pass data from a controller to a view. The
view model approach to passing data is preferred over the ViewData dic onary approach.
Add a Model:
In this sec on, classes are added for managing movies in a database. These classes are the
"Model" part of the MVC app.
These model classes are used with En ty Framework Core (EF Core) to work with a database. EF
Core is an object-rela onal mapping (ORM) framework that simplifies the data access code that
you have to write.
The model classes created are known as POCO classes, from Plain Old CLR Objects. POCO
classes don't have any dependency on EF Core. They only define the proper es of the data to be
stored in the database.
In this tutorial, model classes are created first, and EF Core creates the database.
using System.ComponentModel.DataAnnotations;
namespace MvcMovie.Models;
The Movie class contains an Id field, which is required by the database for the primary key.
The DataType a ribute on ReleaseDate specifies the type of the data (Date). With this a ribute:
Open a command window in the project directory. The project directory is the directory that
contains the Program.cs and .csproj files.
In Visual Studio Code, press Ctrl+F5 to run the app without debugging.
In the Panel below the editor region, select the PROBLEMS tab, or from the View menu,
select Problems if it is not currently in view. Verify there are no compila on errors.
Use the scaffolding tool to produce Create, Read, Update, and Delete (CRUD) pages for the
movie model.
Open a command window in the project directory. The project directory is the directory that
contains the Program.cs and .csproj files.
Parameter Descrip on
--rela veFolderPath The rela ve output folder path to create the files.
--databaseProvider sqlite Specify DbContext should use SQLite instead of SQL Server.
The automa c crea on of these files and file updates is known as scaffolding.
The scaffolded pages can't be used yet because the database doesn't exist. Running the app and
selec ng the Movie App link results in a Cannot open database or no such table: Movie error
message.
Ini al migra on
Use the EF Core Migra ons feature to create the database. Migra ons is a set of tools that
create and update a database to match the data model.
ef database update: Updates the database to the latest migra on, which the previous
command created. This command runs the Up method in the Migra ons/{ me-
stamp}_Ini alCreate.cs file, which creates the database.
There are no movies in the database. You can click the Create New link and start entering
movies.