Creating RazorPagesMovie item (c) based on the ASP.NET core 3.1 - Razor page has been set up to explain the base frame and updates

 

This section focuses on one page set up by Razor pedestal created and do some UI change.

First, create, delete, and edit details page

  1, double-click Pages / Movies / Index.cshtml.cs file, which is a model Razor page:

  

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Mvc;
 6 using Microsoft.AspNetCore.Mvc.RazorPages;
 7 using Microsoft.EntityFrameworkCore;
 8 using RazorPagesMovie.Data;
 9 using RazorPagesMovie.Models;
10 
11 namespace RazorPagesMovie
12 {
13     public class IndexModel : PageModel
14     {
15         private readonly RazorPagesMovie.Data.RazorPagesMovieContext _context;
16 
17         public IndexModel(RazorPagesMovie.Data.RazorPagesMovieContext context)
18         {
19             _context = context;
20         }
21 
22         public IList<Movie> Movie { get;set; }
23 
24         public async Task OnGetAsync()
25         {
26             Movie = await _context.Movie.ToListAsync();
27         }
28     }
29 }

 

 

  ① Line 13: indicates that the page is derived from Razor PageModel. Conventions: PageModel derived class called <PageName> Model.

  ② Line 17: indicates that this is a constructor, using dependency injection will RazorPagesMovieContent added to the page. All pages have been set up base frame follow this pattern.

  ③ Line 24: Indicates when a request for a page, OnGetAsync method returns the list of films to Razor page. OnGetAsync or OnGet call to initialize the page state. Videos list OnGetAsync method will get displayed. When OnGet return void or OnGetAsync return task, using any return statement. At this time, since the return of the Movie Object, made in the program is defined (line 22)

 2, double-click Pages / Movies / Create.cshtml.cs file, which is a model Razor page:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Mvc;
 6 using Microsoft.AspNetCore.Mvc.RazorPages;
 7 using Microsoft.AspNetCore.Mvc.Rendering;
 8 using RazorPagesMovie.Data;
 9 using RazorPagesMovie.Models;
10 
11 namespace RazorPagesMovie
12 {
13     public class CreateModel : PageModel
14     {
15         private readonly RazorPagesMovie.Data.RazorPagesMovieContext _context;
16 
17         public CreateModel(RazorPagesMovie.Data.RazorPagesMovieContext context)
18         {
19             _context = context;
20         }
21 
22         public IActionResult OnGet()
23         {
24             return Page();
25         }
26 
27         [BindProperty]
28         public Movie Movie { get; set; }
29 
30         // To protect from overposting attacks, please enable the specific properties you want to bind to, for
31         // more details see https://aka.ms/RazorPagesCRUD.
32         public async Task<IActionResult> OnPostAsync()
33         {
34             if (!ModelState.IsValid)
35             {
36                 return Page();
37             }
38 
39             _context.Movie.Add(Movie);
40             await _context.SaveChangesAsync();
41 
42             return RedirectToPage("./Index");
43         }
44     }
45 }

 

  ④ The first line 32, 22: if the return type is IActionResult or Task <IActionResult> must be provided when a return statement.

   3, double-click Pages / Movies / Index.cshtml file, which is a Razor page:

 1 @page
 2 @model RazorPagesMovie.IndexModel
 3 
 4 @{
 5     ViewData["Title"] = "Index";
 6 }
 7 
 8 <h1>Index</h1>
 9 
10 <p>
11     <a asp-page="Create">Create New</a>
12 </p>
13 <table class="table">
14     <thead>
15         <tr>
16             <th>
17                 @Html.DisplayNameFor(model => model.Movie[0].Title)
18             </th>
19             <th>
20                 @Html.DisplayNameFor(model => model.Movie[0].ReleaseDate)
21             </th>
22             <th>
23                 @Html.DisplayNameFor(model => model.Movie[0].Genre)
24             </th>
25             <th>
26                 @Html.DisplayNameFor(model => model.Movie[0].Price)
27             </th>
28             <th></th>
29         </tr>
30     </thead>
31     <tbody>
32 @foreach (var item in Model.Movie) {
33         <tr>
34             <td>
35                 @Html.DisplayFor(modelItem => item.Title)
36             </td>
37             <td>
38                 @Html.DisplayFor(modelItem => item.ReleaseDate)
39             </td>
40             <td>
41                 @Html.DisplayFor(modelItem => item.Genre)
42             </td>
43             <td>
44                 @Html.DisplayFor(modelItem => item.Price)
45             </td>
46             <td>
47                 <a asp-page="./Edit" asp-route-id="@item.ID">Edit</a> |
48                 <a asp-page="./Details" asp-route-id="@item.ID">Details</a> |
49                 <a asp-page="./Delete" asp-route-id="@item.ID">Delete</a>
50             </td>
51         </tr>
52 }
53     </tbody>
54 </table>

 

 

  Razor may be converted from HTML to C # or Razor specific tags. When behind the @ symbol followed by a keyword reserved Razor, Razor it is converted to a specific tag, otherwise it will be converted to C #.

  ① Line 1: @page instruction, which is an example of a Razor instruction. This command indicates to convert the file to a MVC operation. This means that it can process the request. @page must be the first page of a Razor instruction.

  ② 17-26 Line: @Html This is a series of Lambda expressions using HTML Help program. DisplayNameFor HTML Help program to check the Lambda expressions cited Tile, ReleaseDate and other property to determine the display name. Check the Lambda expressions (but not evaluated), mean model, model.Movie or model.Movie [0] is null or empty, there is not any access violation.

  The first line ③ 35-44: @ Html.DisplayFor Lambda expressions is evaluated and obtain the attribute values ​​of the model.

  ④ Line 2: @model instruction is transmitted to the specified model type Razor page. Model type in this example, is derived in paragraph 1 PageModel IndexModel model class.

  Razor behind no keyword @ symbol indicates that this is an example of C #: ⑤ line 4-6. Braces {} is C # code blocks. Model of the page is referenced IndexModel, it is derived from PageModel, PageModel ViewData dictionary contains the base class attributes, it may be used to pass data to a view. Key-value pair model we can use to add objects to the ViewData dictionary. Here, "Title" attribute is added to the ViewData dictionary. The "Title" attribute has been used /Pages/Shared/_Layout.cshtml file. See section ③ article comments in Section 4.

   4, double-click the file /Pages/Shared/_Layout.cshtml

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="utf-8" />
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 6     <title>@ViewData["Title"] - RazorPagesMovie</title>
 7     <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
 8     <link rel="stylesheet" href="~/css/site.css" />
 9 </head>
10 <body>
11     <header>
12         <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
13             <div class="container">
14                 <a class="navbar-brand" asp-area="" asp-page="/Index">RazorPagesMovie</a>
15                 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
16                         aria-expanded="false" aria-label="Toggle navigation">
17                     <span class="navbar-toggler-icon"></span>
18                 </button>
19                 <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
20                     <ul class="navbar-nav flex-grow-1">
21                         <li class="nav-item">
22                             <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
23                         </li>
24                         <li class="nav-item">
25                             <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
26                         </li>
27                     </ul>
28                 </div>
29             </div>
30         </nav>
31     </header>
32     <div class="container">
33         <main role="main" class="pb-3">
34             @RenderBody()
35         </main>
36     </div>
37 
38     <footer class="border-top footer text-muted">
39         <div class="container">
40             &copy; 2019 - RazorPagesMovie - <a asp-area="" asp-page="/Privacy">Privacy</a>
41         </div>
42     </footer>
43 
44     <script src="~/lib/jquery/dist/jquery.min.js"></script>
45     <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
46     <script src="~/js/site.js" asp-append-version="true"></script>
47 
48     @RenderSection("Scripts", required: false)
49 </body>
50 </html>

  ① This is a page layout template (similar to a master page). It allows the container has HTML layout: In a specified location; applied to a plurality of pages sites.

  ② Line 34: @RenderBody (), is a placeholder for all pages of the specific view.

  ③ at line 6: @ViewData [ "Title"] values ​​of the dictionary object "Title" taken out, and the string '- RazorPagesMovie' together. The final form of the title page we see:

  

 

 

   Comment way ④ Razor pages using: @ * @ * footnotes to annotate the way (different from the HTML comments <- comment -!>). Comments are not sent to the client

 

 5, the layout update

  ① Change Title and Links page

    /Pages/Shared/_Layout.cshtml file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - 电影</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</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">
<a class="navbar-brand" asp-page="/Movies/Index">我的电影</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>

 

    Where a total change at 2:

    <title>@ViewData["Title"] - 电影</title>   

    <a class="navbar-brand" asp-page="/Movies/Index">我的电影</a>

    Wherein the second change, the original code: asp-area = "" asp-page = "/ Movies / Index">, which represents a helper marker. After the change, it is a program to help anchor tag. asp-page = "/ Movies / Index" marks the attribute and value help of the program can create a connection point / Movies / Index of Razor pages. Wherein, asp-area attribute value is null, indicating that the connection unused area.

  Pages / Movies / Index.cshtml file:

@page
@model RazorPagesMovie.IndexModel

@{
ViewData["Title"] = "首页";
}

<H1> Home </ h1>

 

  Pages / _ViewStart.cshtml set Layout properties:

1 @{
2     Layout = "_Layout";
3 }

 

    This tag for all Razor file layout file is set to Pages Pages folder under / Shared / _Layout.cshtml.

  Pages / Movies / Create.cshtml.cs file:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Mvc;
 6 using Microsoft.AspNetCore.Mvc.RazorPages;
 7 using Microsoft.AspNetCore.Mvc.Rendering;
 8 using RazorPagesMovie.Data;
 9 using RazorPagesMovie.Models;
10 
11 namespace RazorPagesMovie
12 {
13     public class CreateModel : PageModel
14     {
15         private readonly RazorPagesMovie.Data.RazorPagesMovieContext _context;
16 
17         public CreateModel(RazorPagesMovie.Data.RazorPagesMovieContext context)
18         {
19             _context = context;
20         }
21 
22         public IActionResult OnGet()
23         {
24             return Page();
25         }
26 
27         [BindProperty]
28         public Movie Movie { get; set; }
29 
30         // To protect from overposting attacks, please enable the specific properties you want to bind to, for
31         // more details see https://aka.ms/RazorPagesCRUD.
32         public async Task<IActionResult> OnPostAsync()
33         {
34             if (!ModelState.IsValid)
35             {
36                 return Page();
37             }
38 
39             _context.Movie.Add(Movie);
40             await _context.SaveChangesAsync();
41 
42             return RedirectToPage("./Index");
43         }
44     }
45 }

 

   Line 22: The method of any state required OnGet initial page. Create page does not have any state to be initialized and therefore return Page (), Page () method creates an object used to render Create.cshtml PageResult page. Later, we will continue to study the example OnGet initialization state.

     The 27th line: Use [the bindProperty] characteristics, Movie attribute added to the selected model binding. When the Create page release form values ​​(form tag), ASP.NET Core runtime release (post return) value is bound to the Movie model.

     Line 32: When the page is posted (post) form (form) data, will run OnGetAsync method.

     34-37 Line: If any model error does not exist, will re-display the form, and any form data back post. Before post back to form, the model can capture most of the errors on the client. An example of the model is wrong: post date field value can not be converted back to a date.

     Line 39-42: if the model error does not exist, save the data. Finally, the browser will be redirected to the Index page.

  Open, update Pages / Movies / Create.cshtml's Razor page:

  

 1 @page
 2 @model RazorPagesMovie.CreateModel
 3 
 4 @{
 5     ViewData["Title"] = "添加";
 6 }
 7 
 8 <h1>新增</h1>
 9 
10 <h4>电影</h4>
11 <hr />
12 <div class="row">
13     <div class="col-md-4">
14         <form method="post">
15             <div asp-validation-summary="ModelOnly" class="text-danger"></div>
16             <div class="form-group">
17                 <label asp-for="Movie.Title" class="control-label">标题</label>
18                 <input asp-for="Movie.Title" class="form-control" />
19                 <span asp-validation-for="Movie.Title" class="text-danger"></span>
20             </div>
21             <div class="form-group">
22                 <label asp-for="Movie.ReleaseDate" class="control-label">发布时间</label>
23                 <input asp-for="Movie.ReleaseDate" class="form-control" />
24                 <span asp-validation-for="Movie.ReleaseDate" class="text-danger"></span>
25             </div>
26             <div class="form-group">
27                 <label asp-for="Movie.Genre" class="control-label">题材</label>
28                 <input asp-for="Movie.Genre" class="form-control" />
29                 <span asp-validation-for="Movie.Genre" class="text-danger"></span>
30             </div>
31             <div class="form-group">
32                 <label asp-for="Movie.Price" class="control-label">价格</label>
33                 <input asp-for="Movie.Price" class="form-control" />
34                 <span asp-validation-for="Movie.Price" class="text-danger"></span>
35             </div>
36             <div class="form-group">
37                 <input type="submit" value="添加" class="btn btn-primary" />
38             </div>
39         </form>
40     </div>
41 </div>
42 
43 <div>
44     <a asp-page="Index">返回到电影列表</a>
45 </div>
46 
47 @section Scripts {
48     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
49 }

 

 

    Line 14: that this element is a form tag helper (form tag helper). Help form tag program will automatically include security token (antiforgery token).

    The first line 15-34: Razor engine creates a base frame marker (except ID) for each field in the model.

      Wherein <div asp-validation-summary> and <span asp-validation-for> together displays validation errors. Detailed study again after verifying the information.

      <Label asp-for = "" class = ""> tag is a tag to help program (label tag helper). And generating a description tag for the Title property characteristics. (Here we manually changed to "Title").

      <Input asp_for = "" class = ""> and the attributes used to generate DataAnnotations jQuery client authentication required HTML attributes.

 6. Verify

  Press ctrl + F5, run the application. We tested the effect of the changes.

 

Guess you like

Origin www.cnblogs.com/hiwuchong/p/12081664.html