Murach's ASP.NET Core MVC (2nd Ed.) Chapter 2 PDF

Summary

This document details the creation of a one-page MVC web app using ASP.NET Core MVC. Key components of the document, such as controllers, views, and models, are discussed along with steps for development within Visual Studio.

Full Transcript

Murach’s ASP.NET Core MVC (2nd Ed.) Chapter 2 How to develop a one-page MVC web app © 2023, Mike Murach & Associates, Inc....

Murach’s ASP.NET Core MVC (2nd Ed.) Chapter 2 How to develop a one-page MVC web app © 2023, Mike Murach & Associates, Inc. C2, Slide 1 Objectives (part 1) Applied 1. Given the specifications for a one-page MVC web app, write the C# code for the model and controller classes and write the C# code and HTML for the Razor view. 2. Given an ASP.NET Core MVC web app, run it on your own computer. Knowledge 1. Describe how to use Visual Studio to create an ASP.NET Core project and add the folders and files necessary for an MVC web app. 2. List the names of six folders that are included in an MVC web app by convention. 3. Describe how a controller and its action methods work. C2, Slide 2 Objectives (part 2) 4. Describe how you can use the ViewBag property to transfer data from a controller to a view. 5. Distinguish between a Razor code block and a Razor expression. 6. In general terms, describe how to use the Program.cs file to configure the HTTP request and response pipeline for a simple ASP.NET Core MVC web app. 7. Distinguish between a model class and a controller class. 8. Describe the purpose of a Razor view imports page. 9. Describe how you can use the @model directive and asp-for tag helpers to create a strongly-typed view. 10. Describe how you can use the asp-controller and asp-action tag helpers to specify the controller and action method for a form or a link. C2, Slide 3 Objectives (part 3) 11. Describe how the HttpGet and HttpPost attributes allow you to code action methods so they can handle HTTP GET or POST requests. 12. Describe the purpose of a CSS style sheet for an app. 13. Distinguish between a Razor layout and a Razor view. 14. Describe the purpose of a Razor view start. 15. In general terms, describe how ASP.NET Core MVC provides for validating the data that’s entered by a user. C2, Slide 4 The dialog that displays the project templates C2, Slide 5 The templates presented in this book Template Contains… Web App MVC Starting folders and files for an ASP.NET Core MVC web app. Empty Two starting files for an ASP.NET Core app. How to create a new project  Select FileNewProject from the menu system, select the template you want to use, and then click the Next button. C2, Slide 6 The dialog for configuring a new web app C2, Slide 7 The dialog for providing additional information C2, Slide 8 How to configure an ASP.NET Core MVC web app 1. Enter a project name. 2. Specify the location (folder). To do that, you can click the Browse […] button. 3. Edit the solution name if necessary, and then click the Next button. 4. Use the resulting dialog to provide any additional information for the web app and click Create. C2, Slide 9 Visual Studio with the folders for an MVC web app C2, Slide 10 How to delete files from the MVC template 1. Expand the Controllers folder and delete all files in that folder. 2. Expand the Models folder and delete all files in that folder. 3. Expand the Views folder and its subfolders and delete all files in those folders, but don’t delete the folders. C2, Slide 11 How to add folders to the Empty template 1. Add the Controllers, Models, and Views folders. 2. Within the Views folder, add the Home and Shared folders. C2, Slide 12 The dialogs for adding a controller C2, Slide 13 How to add a file for a controller 1. Right-click the Controllers folder and select AddController. 2. In the Add New Scaffolded Item dialog, select “MVC Controller – Empty” and click Add. 3. In the Add New Item dialog, name the controller and click Add. C2, Slide 14 The HomeController.cs file using Microsoft.AspNetCore.Mvc; namespace FutureValue.Controllers { public class HomeController : Controller { public IActionResult Index() { ViewBag.Name = "Mary"; ViewBag.FV = 99999.99; return View(); } } } C2, Slide 15 The dialogs for adding a Razor view C2, Slide 16 How to add a view to the Views/Home folder 1. In the Solution Explorer, right-click the Views/Home folder and select AddView. 2. In the Add New Scaffolded Item dialog, select Razor View – Empty and click Add. 3. In Add New Item dialog, name the view Index and click Add. C2, Slide 17 The Home/Index.cshtml view @{ Layout = null; } Home Page Future Value Calculator Customer Name: @ViewBag.Name Future Value: @ViewBag.FV.ToString("C2") C2, Slide 18 The Program.cs file that’s generated (part 1) var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. // You may want to change this // for production scenarios, see // https://aka.ms/aspnetcore-hsts. app.UseHsts(); } C2, Slide 19 The Program.cs file that’s generated (part 2) app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); C2, Slide 20 The Start button drop-down list in Visual Studio C2, Slide 21 The Future Value app in the Chrome browser C2, Slide 22 The Error List window in Visual Studio C2, Slide 23 The dialog for adding a class C2, Slide 24 How to add a file for a model class 1. In the Solution Explorer, right-click the Models folder and select AddClass. 2. In the resulting dialog, enter the name of the class, and click the Add button. C2, Slide 25 The FutureValueModel class with three properties and a method namespace FutureValue.Models { public class FutureValueModel { public decimal MonthlyInvestment { get; set; } public decimal YearlyInterestRate { get; set; } public int Years { get; set; } public decimal CalculateFutureValue() { int months = Years * 12; decimal monthlyInterestRate = YearlyInterestRate / 12 / 100; decimal futureValue = 0; for (int i = 0; i < months; i++) { futureValue = (futureValue + MonthlyInvestment) * (1 + monthlyInterestRate); } return futureValue; } } } C2, Slide 26 The dialog for adding a Razor view imports page C2, Slide 27 How to add a Razor view imports page 1. In the Solution Explorer, right-click the Views folder and select AddNew Item. 2. In the resulting dialog, select the InstalledASP.NET CoreWeb category, select the Razor View Imports item, and click the Add button. C2, Slide 28 The Views/_ViewImports.cshtml file for the Future Value app @using FutureValue.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers A Razor view imports page makes it easier to work with…  Model classes.  Tag helpers. C2, Slide 29 Common tag helpers for forms Tag helper HTML tags asp-for asp-action asp-controller C2, Slide 30 A strongly-typed Index view with tag helpers (part 1) @model FutureValueModel @{ Layout = null; } Future Value Calculator Future Value Calculator Monthly Investment: C2, Slide 31 A strongly-typed Index view with tag helpers (part 2) Yearly Interest Rate: Number of Years: Future Value: Calculate Clear C2, Slide 32 Attributes that indicate the HTTP verb an action method handles HttpGet HttpPost Methods for returning a view from a controller View() View(model) C2, Slide 33 An overloaded Index() action method using Microsoft.AspNetCore.Mvc; using FutureValue.Models; public class HomeController : Controller { [HttpGet] public IActionResult Index() { ViewBag.FV = 0; return View(); } [HttpPost] public IActionResult Index(FutureValueModel model) { ViewBag.FV = model.CalculateFutureValue(); return View(model); } } C2, Slide 34 The Future Value app after a GET request C2, Slide 35 The Future Value app after a POST request C2, Slide 36 The dialog for adding a CSS style sheet C2, Slide 37 How to add a CSS style sheet 1. If the wwwroot/css folder doesn’t exist, create it. 2. Right-click the wwwroot/css folder and select AddNew Item. 3. Select the ASP.NET CoreWeb category, select the Style Sheet item, enter a name for the CSS file, and click the Add button. C2, Slide 38 The site.css file for the Future Value app body { padding: 1em; font-family: Arial, Helvetica, sans-serif; } h1 { margin-top: 0; color: navy; } label { display: inline-block; width: 10em; padding-right: 1em; } div { margin-bottom:.5em; } C2, Slide 39 The dialog for adding a Razor layout or view start C2, Slide 40 How to add a Razor layout 1. Right-click the Views/Shared folder and select AddNew Item. 2. Select the ASP.NET CoreWeb category, select the Razor Layout item, and click the Add button. C2, Slide 41 How to add a Razor view start 1. Right-click the Views folder (not the Views/Shared folder) and select AddNew Item. 2. Select the ASP.NET CoreWeb category, select the Razor View Start item, and click the Add button. C2, Slide 42 The Views/Shared/_Layout.cshtml file @ViewBag.Title @RenderBody() The Views/_ViewStart.cshtml file @{ Layout = "_Layout"; } C2, Slide 43 The dialog for adding a Razor view C2, Slide 44 How to add a Razor view 1. Right-click the folder for the view (Views/Home, for example) and select AddView. 2. Use the Add New Scaffolded Item dialog from figure 2-5 to select Razor View, and then click Add. 3. Use the Add Razor View dialog to enter a name for the view, make sure that the “Use a layout page” item is selected, but don’t specify a name for the layout page. C2, Slide 45 The Views/Home/Index.cshtml file @model FutureValueModel @{ ViewData["Title"] = "Future Value Calculator"; } Future Value Calculator Monthly Investment: Yearly Interest Rate: Number of Years: Future Value: @ViewBag.FV.ToString("c2") Calculate Clear C2, Slide 46 How to import the DataAnnotations namespace using System.ComponentModel.DataAnnotations; Two common validation attributes Required Range(min, max) C2, Slide 47 A model property with a validation attribute [Required] public decimal? MonthlyInvestment { get; set; } The default error message if the property isn’t set The field MonthlyInvestment is required. C2, Slide 48 A model property with two validation attributes [Required] [Range(1, 500)] public decimal? MonthlyInvestment { get; set; } The default error message if the property isn’t in a valid range The field MonthlyInvestment must be between 1 and 500. C2, Slide 49 A model property with user-friendly error messages [Required(ErrorMessage = "Please enter a monthly investment amount.")] [Range(1, 500, ErrorMessage = "Monthly investment amount must be between 1 and 500.")] public decimal? MonthlyInvestment { get; set; } C2, Slide 50 The model class with data validation attributes (part 1) using System.ComponentModel.DataAnnotations; 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; } [Required(ErrorMessage = "Please enter a yearly interest rate.")] [Range(0.1, 10.0, ErrorMessage = "Yearly interest rate must be between 0.1 and 10.0.")] public decimal? YearlyInterestRate { get; set; } C2, Slide 51 The model class with data validation attributes (part 2) [Required(ErrorMessage = "Please enter a number of years.")] [Range(1, 50, ErrorMessage = "Number of years must be between 1 and 50.")] public int? Years { get; set; } public decimal? CalculateFutureValue() { int? months = Years * 12; decimal? monthlyInterestRate = YearlyInterestRate / 12 / 100; decimal? futureValue = 0; for (int i = 0; i < months; i++) { futureValue = (futureValue + MonthlyInvestment) * (1 + monthlyInterestRate); } return futureValue; } } } C2, Slide 52 An action method that checks for invalid data [HttpPost] public IActionResult Index(FutureValueModel model) { if (ModelState.IsValid) { ViewBag.FV = model.CalculateFutureValue(); } else { ViewBag.FV = 0; } return View(model); } C2, Slide 53 A view that displays a summary of validation messages Monthly Investment: C2, Slide 54 The Future Value app with invalid data C2, Slide 55

Use Quizgecko on...
Browser
Browser