0% found this document useful (0 votes)
3 views

text01

This document provides a step-by-step guide to creating a .NET Core MVC project using Visual Studio Code, including prerequisites, project setup, and running the application. It covers adding controllers, creating views with Razor, and modifying layout templates to customize the application. The guide emphasizes the routing mechanism, controller actions, and how to pass parameters through URLs, culminating in a fully functional web application.

Uploaded by

abwmbkytnaa
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)
3 views

text01

This document provides a step-by-step guide to creating a .NET Core MVC project using Visual Studio Code, including prerequisites, project setup, and running the application. It covers adding controllers, creating views with Razor, and modifying layout templates to customize the application. The guide emphasizes the routing mechanism, controller actions, and how to pass parameters through URLs, culminating in a fully functional web application.

Uploaded by

abwmbkytnaa
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/ 27

Creating a .

NET Core MVC project using


Visual Studio Code

Prerequisite
 Visual Studio Code

 C# Dev Kit for Visual Studio Code

 .NET 9.0 SDK

Create the App


Select New Terminal from the Terminal menu to open the Integrated Terminal. You can
press Ctrl + ~ or Ctrl + J

Change to the directory (cd) that will contain the project.


cd C:\Users\abdal\OneDrive\Desktop\Spring25\AdvanceWeb\Code\MVCdocs\vscodeExample

Note that in your machine the folder will be different.


Run the following commands:
dotnet new mvc -o MvcMovie
code -r MvcMovie

The first command creates a new project called MvcMovie and create a folder with the
same name containing the project files.

The second command open VScode in the created folder.


Select Yes if Visual Studio Code displays a dialog box that asks: Do you trust the authors of
the files in this folder?

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.

Run the app


Trust the HTTPS development cer ficate by running the following command:
dotnet dev-certs https –trust

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:

 Make code changes.

 Save the file.

 Quickly refresh the browser and see the code changes.


Close the browser window.

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;

public class HelloWorldController : Controller


{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my default action...";
}
//
// GET: /HelloWorld/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
}
Every public method in a controller is callable as an HTTP endpoint. In the sample above, both
methods return a string. Note the comments preceding each method.

An HTTP endpoint:
 Is a targetable URL in the web applica on, such as h ps://localhost:5001/HelloWorld.

 Combines:

o The protocol used: HTTPS.

o The network loca on of the web server, including the TCP port: localhost:5001.

o The target URI: HelloWorld.

The first comment states this is an HTTP GET method that's invoked by
appending /HelloWorld/ to the base URL.

The second comment specifies an HTTP GET method that's invoked by


appending /HelloWorld/Welcome/ to the URL.

Run the app without the debugger by pressing Ctrl+F5.

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]

The rou ng format is set in the Program.cs file:


app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
When you browse to the app and don't supply any URL segments, it defaults to the "Home"
controller and the "Index" method specified in the template line highlighted above. In the
preceding URL segments:

o The first URL segment determines the controller class to run.


So, localhost:5001/HelloWorld maps to the HelloWorld Controller class.

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.

Browse to: h ps://localhost:{PORT}/HelloWorld/Welcome. Replace {PORT} with your port


number.

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.

The HelloWorldController.cs file will look like this:

using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;

namespace MvcMovie.Controllers;

public class HelloWorldController : Controller


{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my default action...";
}
// GET: /HelloWorld/Welcome/
// Requires using System.Text.Encodings.Web;
public string Welcome(string name, int numTimes = 1)
{
return HtmlEncoder.Default.Encode($"Hello {name}, NumTimes is:
{numTimes}");
}
}

The preceding code:

 Uses the C# op onal-parameter feature to indicate that the numTimes parameter


defaults to 1 if no value is passed for that parameter.

 Uses HtmlEncoder.Default.Encode to protect the app from malicious input, such as


through JavaScript.

 Uses Interpolated Strings in $"Hello {name}, NumTimes is: {numTimes}".

Run the app and browse to:

h ps://localhost:{PORT}/HelloWorld/Welcome?name=Rick&num mes=4

Replace {PORT} with your port number.


Try different values for name and num mes in the URL. The MVC model binding system
automa cally maps the named parameters from the query string to parameters in the method.

In the previous image:

 The URL segment Parameters isn't used.

 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.

 The & character separates field-value pairs.

Replace the Welcome method with the following code:

The HelloWorldController.cs file will look like:

using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;

namespace MvcMovie.Controllers;

public class HelloWorldController : Controller


{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my default action...";
}
// GET: /HelloWorld/Welcome/
// Requires using System.Text.Encodings.Web;
public string Welcome(string name, int ID = 1)
{
return HtmlEncoder.Default.Encode($"Hello {name}, ID: {ID}");
}
}
Run the app and enter the following
URL: h ps://localhost:{PORT}/HelloWorld/Welcome/3?name=Rick

In the preceding example:

 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.

 The trailing ? (in id?) indicates the id parameter is op onal


Add a View:
In this sec on, you modify the HelloWorldController class to use Razor view files. This cleanly
encapsulates the process of genera ng HTML responses to a client.

View templates are created using Razor. Razor-based view templates:

 Have a .cshtml file extension.

 Provide an elegant way to create HTML output with C#.

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:

The HelloWorldController.cs file will look like:

using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;

namespace MvcMovie.Controllers;

public class HelloWorldController : Controller


{
//
// GET: /HelloWorld/
public IActionResult Index()
{
return View();
}
// GET: /HelloWorld/Welcome/
// Requires using System.Text.Encodings.Web;
public string Welcome(string name, int ID = 1)
{
return HtmlEncoder.Default.Encode($"Hello {name}, ID: {ID}");
}
}
The preceding code:

 Calls the controller's View method.

 Uses a view template to generate an HTML response.

Controller methods:

 Are referred to as ac on methods. For example, the Index ac on method in the


preceding code.
 Generally, return an IAc onResult or a class derived from IAc onResult , not a type
like string.

Add an Index view for the HelloWorldController:

 Add a new folder named HelloWorld to the Views folder.

 Add a new file to the Views/HelloWorld folder, and name it Index.cshtml.

Replace the contents of the Views/HelloWorld/Index.cshtml Razor view file with the following:

@{
ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>Hello from our View Template!</p>

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.

Open the Views/Shared/_Layout.cshtml file.

Layout templates allow:

 Specifying the HTML container layout of a site in one place.

 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>

<footer class="border-top footer text-muted">


<div class="container">
&copy; 2025 - Movie App - <a asp-area="" asp-controller="Home" asp-
action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
The preceding markup made the following changes:

 Three occurrences of MvcMovie to Movie App.

 The anchor element <a class="navbar-brand" asp-area="" asp-controller="Home" asp-


ac on="Index">MvcMovie</a> to <a class="navbar-brand" asp-controller="Movies" asp-
ac on="Index">Movie App</a>.

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.

Examine the Views/_ViewStart.cshtml file:


The Views/_ViewStart.cshtml file brings in the Views/Shared/_Layout.cshtml file to each view.
The Layout property can be used to set a different layout view, or set it to null so no layout file
will be used.

Open the Views/HelloWorld/Index.cshtml view file.

Change the tle and <h2> element as highlighted in the following:

@{
ViewData["Title"] = "Movie List";
}

<h2>My Movie List</h2>

<p>Hello from our View Template!</p>

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:

Save the change and navigate to h ps://localhost:{PORT}/HelloWorld.

No ce that the following have changed:

 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.

The content in the Index.cshtml view template is merged with


the Views/Shared/_Layout.cshtml view template. A single HTML response is sent to the
browser. Layout templates make it easy to make changes that apply across all of the pages in an
app.
The small bit of "data", the "Hello from our View Template!" message, is hard-coded however.
The MVC applica on has a "V" (view), a "C" (controller), but no "M" (model) yet.

Passing Data from the Controller to the View

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.

View templates should not:

 Do business logic

 Interact with a database directly.

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.

In HelloWorldController.cs, change the Welcome method to add


a Message and NumTimes value to the ViewData dic onary.

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;

public class HelloWorldController : Controller


{
public IActionResult Index()
{
return View();
}
public IActionResult Welcome(string name, int numTimes = 1)
{
ViewData["Message"] = "Hello " + name;
ViewData["NumTimes"] = numTimes;
return View();
}
}

The ViewData dic onary object contains data that will be passed to the view.

Create a Welcome view template named Views/HelloWorld/Welcome.cshtml.

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>

Save your changes and browse to the following URL:

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.

Add a file named Movie.cs to the Models folder.

Update the Models/Movie.cs file with the following code:

using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models;

public class Movie


{
public int Id { get; set; }
public string? Title { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string? Genre { get; set; }
public decimal Price { get; set; }
}

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:

 The user isn't required to enter me informa on in the date field.

 Only the date is displayed, not me informa on.

The ques on mark a er string indicates that the property is nullable.

Add NuGet packages

Open a command window in the project directory. The project directory is the directory that
contains the Program.cs and .csproj files.

Run the following .NET CLI commands:


dotnet tool uninstall --global dotnet-aspnet-codegenerator
dotnet tool install --global dotnet-aspnet-codegenerator
dotnet tool uninstall --global dotnet-ef
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SQLite
dotnet add package
Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

The preceding commands add:

 The command-line interface (CLI) tools for EF Core

 The aspnet-codegenerator scaffolding tool.

 Design me tools for EF Core


 The EF Core SQLite provider, which installs the EF Core package as a dependency.

 Packages needed for scaffolding:

Microso .VisualStudio.Web.CodeGenera on.Design and Microso .En tyFrameworkCore.SqlSer


ver.

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.

Scaffold movie pages

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.

Run the following command:


dotnet aspnet-codegenerator controller -name MoviesController -m
Movie -dc MvcMovie.Data.MvcMovieContext --relativeFolderPath
Controllers --useDefaultLayout --referenceScriptLibraries --
databaseProvider sqlite
The following table details the ASP.NET Core code generator parameters:

Parameter Descrip on

-m The name of the model.

-dc The data context.

--rela veFolderPath The rela ve output folder path to create the files.

--useDefaultLayout|-udl The default layout should be used for the views.

--referenceScriptLibraries Adds _Valida onScriptsPar al to Edit and Create pages.

--databaseProvider sqlite Specify DbContext should use SQLite instead of SQL Server.

Scaffolding creates the following:

 A movies controller: Controllers/MoviesController.cs

 Razor view files for Create, Delete, Details, Edit,


and Index pages: Views/Movies/*.cshtml

 A database context class: Data/MvcMovieContext.cs

Scaffolding updates the following:


 Registers the database context in the Program.cs file

 Adds a database connec on string to the appse ngs.json file.

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.

Build the app to verify that there are no errors.


dotnet build

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.

Run the following .NET CLI command:


dotnet ef migrations add InitialCreate

 ef migra ons add Ini alCreate: Generates


a Migra ons/{ mestamp}_Ini alCreate.cs migra on file. The Ini alCreate argument is
the migra on name. Any name can be used, but by conven on, a name is selected that
describes the migra on. This is the first migra on, so the generated class contains code
to create the database schema. The database schema is based on the model specified in
the MvcMovieContext class, in the Data/MvcMovieContext.cs file.

The following warning might be displayed, which is addressed in a later step:


No store type was specified for the decimal property 'Price' on en ty type 'Movie'. This will
cause values to be silently truncated if they do not fit in the default precision and scale.
Explicitly specify the SQL server column type that can accommodate all the values in
'OnModelCrea ng' using 'HasColumnType', specify precision and scale using 'HasPrecision', or
configure a value converter using 'HasConversion'.

Run the following .NET CLI command:


dotnet ef database update

 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.

Run the app and select the Movie App link.

There are no movies in the database. You can click the Create New link and start entering
movies.

You might also like