CH 02
CH 02
murach’s
ASP.NET
Core MVC
(Chapter 2)
Thanks for downloading this chapter from Murach’s ASP.NET Core MVC. We hope
it will show you how easy it is to learn from any Murach book, with its paired-pages
presentation, its “how-to” headings, its practical coding examples, and its clear, concise
style.
To view the full table of contents for this book, you can go to our website. From there,
you can read more about this book, you can find out about any additional downloads that
are available, and you can review our other books on related topics.
Thanks for your interest in our books!
“I purchased several ASP.NET books but didn’t really learn it until I purchased
this one.”
J.R., Enterprise Developer, Florida
“After reading several other books, I still was not able to get my webpage to
work the way I wanted. After reading Murach’s book, it works perfectly.”
Harold E. Luse, posted online
“Another awesome book from Murach. Their format makes learning new
material easier, and their code examples WORK.”
Posted at an online bookseller
“Another thing I like is the exercises at the end of each chapter. They’re a great
way to reinforce the main points of each chapter and force you to get your
hands dirty.”
Hien Luu, SD Forum/Java SIG
“I kept your book at my side throughout the entire project. It was indispensable
to me. The answers were right there at every turn. All the examples made sense
to me, and they all worked!”
Alan Vogt, ETL Consultant, Massachusetts
Description
•• If the “Place solution and project in the same directory” box is unchecked, Visual
Studio creates a folder for the solution and a subfolder for the project. Otherwise,
these files are stored in the same folder.
Description
•• When starting an ASP.NET Core web app, Visual Studio provides several templates
that you can use.
•• For this chapter, we recommend using the Web Application (Model-View-
Controller) template, also known as the MVC template, because it makes it easy to
start an ASP.NET Core MVC web app.
•• If you want to manually build your web app from scratch, you can use the Empty
template.
Visual Studio after the folders have been set up for an MVC web app
Description
•• To add a folder, you can right-click a node and select AddNew Folder.
•• To delete a folder or file, you can right-click the folder or file and select Delete.
namespace FutureValue.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Name = "Mary";
ViewBag.FV = 99999.99;
return View();
}
}
}
Description
•• A method of a controller that runs in response to HTTP action verbs such as GET
or POST is known as an action method, or an action.
•• The ViewBag property is automatically available to controllers and views. It uses
dynamic properties to get and set values.
•• The View() method returns a ViewResult object for the view associated with an
action method.
Description
•• A Razor view contains both C# code and HTML. That’s why its file extension is .cshtml.
•• In ASP.NET Core MVC, the Razor view engine uses server-side code to embed C# code
within HTML elements.
•• To execute one or more C# statements, you can declare a Razor code block by coding the @
sign followed by a pair of curly braces ({ }).
•• To evaluate a C# expression and display its result, you can code a Razor expression
by coding the @ sign and then coding the expression.
namespace FutureValue
{
public class Startup
{
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Description
•• The Startup.cs file contains the code that configures the middleware for the HTTP
request pipeline.
•• The Configure() method begins by checking whether the web hosting environment
is a development environment. If so, it configures the middleware for a
development environment. Otherwise, it configurations the middleware for a
production environment.
•• The UseEndpoints() method in this figure sets the default controller for the app to
the Home controller, and it sets the default action to the Index() action. As a result,
when the app starts, it calls the Index() action method of the Home controller.
Figure 2-6 How to configure an MVC web app
50 Section 1 Get off to a fast start
Description
•• To run an app in the default browser, press Ctrl+F5. This starts the app without
debugging.
•• To stop an app, click the close button in the browser’s upper right corner.
•• To change the default browser for the app, display the drop-down list for the Start
button, select the Web Browser item, and select the default web browser from the
list.
•• By default, Visual Studio uses the IIS Express web server. To change the web
server to the Kestrel server, display the drop-down list for the Start button and
select the project’s name.
•• When Visual Studio runs the app on the Kestrel server, it uses a console window
to display information about the server. To stop the server, you can close the
command line window.
•• If you press F5 or click the Start button in the toolbar, Visual Studio starts the app
with debugging. This is another way to run an app that’s especially useful if you
need to debug an app as described in chapter 5. Then, to stop the app, you can click
the Stop Debugging button in the Debug toolbar.
Figure 2-7 How to run a web app
52 Section 1 Get off to a fast start
Description
•• If a syntax error is detected when you attempt to build and run an app, a dialog asks
whether you want to continue by running the last successful build. If you click No,
the app isn’t run and an Error List window is displayed.
•• The Error List window provides information about the errors in your app.
•• To go to the statement that caused a syntax error, double-click the error in the Error
List window. This should help you find the cause of the error.
•• If a compiled statement can’t be executed when you run a web app, an exception
occurs. Then, you can use the information that’s displayed in the browser to attempt
to fix this exception, or you can debug the exception as described in chapter 5.
Description
•• A model is a regular C# class that models the data for the app. The class for a
model is typically stored in the Models folder.
•• A model can’t have the same name as the namespace.
Description
•• Most apps include a Razor view imports page that makes it easier to work with your
model classes and the tag helpers that are available from ASP.NET Core MVC.
Description
•• You use the @model directive to bind the model to the view. This kind of view is
called a strongly-typed view.
•• ASP.NET Core MVC tag helpers are used to automatically generate attributes for
some HTML elements. They are also used to bind HTML elements to the properties
of the object that’s the model for the view.
Figure 2-11 How to code a strongly-typed view
60 Section 1 Get off to a fast start
Two attributes that indicate the HTTP verb an action method handles
Attribute Description
HttpGet Specifies that the action method handles a GET request.
HttpPost Specifies that the action method handles a POST request.
[HttpPost]
public IActionResult Index(FutureValueModel model)
{
ViewBag.FV = model.CalculateFutureValue();
return View(model);
}
}
Description
•• A common pattern in web development is for the same URL to handle HTTP GET
and POST requests. In particular, it’s common to use a GET request for a URL to
display a blank input form to the user. Then, a POST request for the same URL can
process the data that’s submitted when the user fills out the form and submits it.
•• In MVC, you can use overloaded action methods to handle both GET and POST
requests for a page. When you do, you use HTTP attributes to indicate which action
method handles which request.
•• When an action method handles a POST request from a strongly-typed view, MVC
uses the data stored in the POST request to set the properties of the model object.
Then, the action method can use the model object to work with the posted data, and
it can use the View() method to pass the model on to the view.
Description
•• When the Future Value app starts, it sends a GET request to the Index() action of
the Home controller.
•• When the user clicks the Clear link, the app sends a GET request to the Index()
action of the Home controller.
•• When the user clicks the Calculate button, the app sends a POST request to the
Index() action of the Home controller. If the user has filled out the form correctly,
this automatically sets the three properties of the model object.
Figure 2-13 The Future Value app after handling GET and POST requests
64 Section 1 Get off to a fast start
h1 {
margin-top: 0;
color: navy;
}
label {
display: inline-block;
width: 10em;
padding-right: 1em;
}
div {
margin-bottom: .5em;
}
Description
•• A CSS style sheet provides a way to store the formatting for multiple web pages in
a single external file.
Description
•• A Razor layout provides a way to store elements that are common to multiple web
pages in a single file.
•• A Razor view start lets you specify the default Razor layout for the Razor views of
a web app.
•• A Razor view provides a way to store elements that are unique to a web page.
Figure 2-15 How to add a Razor layout, view start, and view
68 Section 1 Get off to a fast start
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<link rel="stylesheet" href="~/css/custom.css" />
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
Description
•• You can use the Razor file named _ViewStart to set the default layout for all the
views in your app. However, if necessary, you can use the Layout property of a
view to override the default layout.
Figure 2-16 The code for a Razor layout, view start, and view
70 Section 1 Get off to a fast start
Description
•• The process of checking data to make sure it’s valid is known as data validation.
•• You can use the validation attributes of the DataAnnotations namespace to add
validation rules to your model.
•• For the Required attribute to work properly, the data type for the property must be
nullable.
•• If you don’t specify an error message, the data validation attributes generate a
default error message.
•• To specify a custom error message, you can pass an argument named ErrorMessage
as the last argument of the attribute.
namespace FutureValue.Models
{
public class FutureValueModel
{
[Required(ErrorMessage = "Please enter a monthly investment.")]
[Range(1, 500, ErrorMessage =
"Monthly investment amount must be between 1 and 500.")]
public decimal? MonthlyInvestment { get; set; }
Description
•• A controller can use the ModelState property that’s available from the controller
class to check whether the data in the model is valid.
•• A view can use the tag helper named asp-validation-summary to display a summary
of all data validation errors in the model.
Figure 2-19 How to check data validation and display error messages
76 Section 1 Get off to a fast start
Perspective
The purpose of this chapter has been to teach you the basic skills for
creating a one-page ASP.NET Core MVC app with Visual Studio. If you’ve
already used Visual Studio and C# to develop other apps, such as Windows
Forms apps, and you have basic HTML and CSS skills, you shouldn’t have any
trouble mastering these skills.
In the next chapter, you’ll learn the basics of using Bootstrap. This
open-source library provides CSS and JavaScript classes that make it easy to
give your pages a professional appearance. In addition, Bootstrap makes it
possible to display your web pages on devices of varying sizes.
Terms
Visual Studio template model
controller Razor view imports page
action method strongly-typed view
action tag helper
Razor view engine CSS style sheet
Razor view Razor layout
Razor code block Razor view start
Razor expression data validation
syntax error validation attributes
exception validation rules
Summary
•• You create a web app from a Visual Studio template that determines the
folders and files for the project.
•• A method of a controller class that runs in response to HTTP action
verbs such as GET or POST is known as an action method, or an action.
•• In ASP.NET Core MVC, the Razor view engine uses server-side code to
embed C# code within HTML elements.
•• A Razor view contains both C# and HTML code. That’s why its file
extension is .cshtml. A Razor view typically stores elements that are
unique to a web page.
•• To execute one or more C# statements, you can declare a Razor code
block by coding the @ sign followed by a pair of curly braces ({ }).
Within the curly braces, you can code one or more C# statements.
•• To evaluate a C# expression and display its result, you can code a Razor
expression by coding the @ sign and then coding the expression.
Chapter 2 How to develop a single-page MVC web app 77
•• When you attempt to build and run an app, Visual Studio may display
syntax errors that have to be corrected before the app can be compiled.
•• If a compiled statement can’t be executed when you run a web app, an
exception occurs. Then, you can use the information that’s displayed in
the browser to attempt to fix the exception.
•• A model is a regular C# class that models the data for the app. The class
for a model is typically stored in the Models folder.
•• A Razor view imports page makes it easier to work with models and tag
helpers. As a result, most web apps include a Razor view imports page.
•• You use the @model directive to bind a model to a view. This kind of
view is called a strongly-typed view.
•• You can use the @Model property to access the properties and methods
of the model object that’s specified by the @model directive.
•• Tag helpers automatically generate attributes for some HTML elements.
They can also bind HTML elements to the properties of the object that’s
the model for the view.
•• A CSS style sheet provides a way to store the formatting for multiple
web pages in a single external file.
•• A Razor layout provides a way to store elements that are common to
multiple web pages in a single file.
•• A Razor view start lets you specify the default Razor layout for the
Razor views of a web app.
•• The process of checking data to make sure it’s valid is known as data
validation.
•• You can use the validation attributes to add validation rules to your
model.
78 Section 1 Get off to a fast start
Add the Razor layout and view start, and modify the Razor view
13. Add a custom.css file to the wwwroot/css folder. If necessary, create this
folder first. Then, modify it so it contains the CSS style rules shown in figure
2-14. To do that, you can cut the CSS style rules from the Home/Index file
and paste them into the custom.css file.
14. Add a Razor layout named _Layout.cshtml to the Views/Shared folder and
modify it so it contains the code shown in figure 2-16. Make sure to include a
<link> element that points to the custom.css file.
15. Add a Razor view start named _ViewStart to the Views folder (not the Views/
Shared folder) and modify it so it contains the code shown in figure 2-16.
16. Modify the code in Home/Index view so it contains the code shown in figure
2-16. To do that, you can cut all elements that are already specified by the
Razor layout.
17. Run the app. It should work the same as it did before.
Add data validation to the Future Value app
18. Modify the FutureValueModel class so it specifies the Required and Range
attributes as shown in figure 2-18. To do that, you must use nullable types for
the properties and the method.
19. Modify the HomeController class so it checks for invalid data as shown in
figure 2-19.
20. Modify the Home/Index view so it displays a summary of validation messages
as shown in figure 2-19.
21. Run the app. It should work correctly if you enter valid data, and it should
display appropriate messages if you enter invalid data.
• Look up coding details or refresh your memory on forgotten details when you’re in
the middle of developing a web app
• Loan to your colleagues who are always asking you questions about ASP.NET
Core MVC programming
To get your copy, you can order online at www.murach.com or call us at
1-800-221-5528 (toll-free in the U.S. and Canada). And remember, when you order
directly from us, this book comes with my personal guarantee:
100% Guarantee
When you buy directly from us, you must be
satisfied. Try our books for 30 days or our eBooks
for 14 days. They must outperform any competing
book or course you’ve ever tried, or return your
purchase for a prompt refund.…no questions asked.