• 06. Asp.Net Core 3.x 笔记Razor Page


    基本配置

    Startup.cs

    
     public class Startup
        {
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages(); //RazorPages
                ....
            }
    
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
               ...
               //RazorPages
               app.UseEndpoints(endpoints =>
                {
                    endpoints.MapRazorPages();
                });
            }
        }
    
    

    Pages

    Pages/Shared/_Layout.cshtml

    ...
     @RenderBody()
    ...
    
    

    _ViewStart.cshtml

    @{
        Layout = "_Layout";
    }
    

    _ViewImports.cshtml

     @using ThreeRazorPage
     @namespace ThreeRazorPage.Pages
     @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
     @addTagHelper "*, ThreeRazorPage"
    

    Index.cshtml

    @page
    @using Three.Models
    @using Three.Services
    
    @inject IDepartmentService departmentService;
    
    <div class="row">
        <div class="col-md-10 offset-md-2">
            <table class="table">
                <tr>
                    <th>Name</th>
                    <th>Location</th>
                    <th>Employee</th>
                    <th>操作</th>
                </tr>
                @Html.DisplayFor(p => p.departments)
            </table>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-4">
            @await Component.InvokeAsync("CompanySummary", new { title = "汇总" })
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-4">
            <vc:company-summary title="汇总2"></vc:company-summary>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-4">
            <a asp-page="Department/AddDepartment">Add</a>
        </div>
    </div>
    
    
    @functions{
        public IEnumerable<Three.Models.Department> departments { get; set; }
        public async Task OnGetAsync()
        {
            departments = await departmentService.GetAll();
        }
    
    }
    

    要点

    asp-page的跳转

    <a asp-page="Department/AddDepartment">Add</a>
    

    依赖注入

    @inject IDepartmentService departmentService;
    

    OnGetAsync 获取本页面

        public async Task OnGetAsync()
        {
            departments = await departmentService.GetAll();
        }
    

    DisplayTemplates

       @Html.DisplayFor(p => p.departments)
    

    ​ 使用的是 Pages/DisplayTemplates/Department.cshtml:

    
    @model Three.Models.Department
    @inject Microsoft.Extensions.Options.IOptions<Three.ThreeOptions> options
        <tr>
    
            @if (Model.EmployeeCount > options.Value.BoldDepartmentEmployeeCountThreshold)
            {
    
                <td><strong>@Model.Name</strong></td>
            }
            else
            {
    
                <td>@Model.Name</td>
            }
    
            <td>@Model.Loaciton</td>
            <td>@Model.EmployeeCount</td>
            <td>
                <a asp-page="Employee/EmployeeList"  asp-route-departmentId="@Model.Id">
                    Employees
                </a>
            </td>
        </tr>
    
    

    Component组件

    • 使用Component的两种调用方式:
    <div>
        <vc:company-summary title="汇总2"></vc:company-summary>
    </div> 
    <div>
        @await Component.InvokeAsync("CompanySummary", new { title = "汇总" })
    </div> 
    
    • Component的定义包括两部分:

    • Pages/Components/CompanySummary/Default.cshtml

      @model Three.Models.CompanySummary
      
          <div class="small">
              <div class="row h3">
                  @ViewBag.Title
              </div>
              <div class="row">
                  <div class="col-md-8">
                      员工人数:
                  </div>
                  <div class="col-md-4">
                      @Model.EmployeeCount
                  </div>
              </div>
              <div class="row">
                  <div class="col-md-8">
                      部门平均人数:
                  </div>
                  <div class="col-md-4">
                      @Model.AvgDepartmentEmployeeCount
                  </div>
              </div>
          </div>
      
    • ViewComponents/CompanySummaryViewComponent.cs

      namespace ThreeRazorPage.ViewComponents
      {
          public class CompanySummaryViewComponent : ViewComponent
          {
              private readonly IDepartmentService departmentService;
              public CompanySummaryViewComponent(IDepartmentService departmentService)
              {
                  this.departmentService = departmentService;
              }
      
              public async Task<IViewComponentResult> InvokeAsync(String title)
              {
                  ViewBag.Title = title;
                  var summary = await departmentService.GetCompanySummary();
                  return View(summary);
              }
          }
      }
      

    添加RazorPage

    在Pages文件夹下,选择“添加/Razor页面”,名称为“AddDepartment.cshtml”,将自动生成 AddDepartment.cshtmlAddDepartment.cshtml.cs

    • AddDepartment.cshtml.cs

        public class AddDepartmentModel : PageModel
          {
              private readonly IDepartmentService departmentService;
      
              [BindProperty]
              public Three.Models.Department Department { get; set; }
      
      
              public AddDepartmentModel(IDepartmentService departmentService)
              {
                  this.departmentService = departmentService;
              }
      
              public async Task<IActionResult> OnPostAsync()
              {
                  if (!ModelState.IsValid)
                  {
                      return Page();
                  }
      
                  await departmentService.Add(Department);
      
                  return RedirectToPage("/Index");
              }
          }
      
    • AddDepartment.cshtml

      @page
      @model ThreeRazorPage.Pages.Department.AddDepartmentModel
      
      <form asp-action="Add">
          <div class="row form-group">
              <div class="col-md-2 offset-md-2">
                  <label asp-for="Department.Name"></label>
              </div>
              <div class="col-md-6">
                  <input class="form-control" asp-for="Department.Name" />
              </div>
          </div>
          <div class="row form-group">
              <div class="col-md-2 offset-md-2">
                  <label asp-for="Department.Loaciton"></label>
              </div>
              <div class="col-md-6">
                  <input class="form-control" asp-for="Department.Loaciton" />
              </div>
          </div>
          <div class="row form-group">
              <div class="col-md-2 offset-md-2">
                  <label asp-for="Department.EmployeeCount"></label>
              </div>
              <div class="col-md-6">
                  <input class="form-control" asp-for="Department.EmployeeCount" />
              </div>
          </div>
          <div class="row">
              <div class="col-md-2 offset-md-2">
                  <button type="submit" class="btn btn-primary">Add</button>
              </div>
          </div>
      </form>
      
      

    要点:

    [BindProperty]

    当在Page页中定义的Mode是

      @model ThreeRazorPage.Pages.Department.AddDepartmentModel
    

    而实际绑定的是Three.Models.Department Department ,则使用[BindProperty]

        public class AddDepartmentModel : PageModel{
            ...
            [BindProperty]
            public Three.Models.Department Department { get; set; }      
            ...
        }
    

    @page 和 @model

    @page
    @model ThreeRazorPage.Pages.Department.AddDepartmentModel
    

    添加PageRazor空页

    新建文件夹 Pages/Employee,并且在其下面,选择“添加/Razor视图- 空”,名称为“EmployeeList.cshtml”

    • EmployeeList.cshtm
    @page "{departmentId:int}"
    @using Microsoft.AspNetCore.Mvc.RazorPages
    @using Three.Services
    @using Three.Models
    @model EmployeeListMode
    
    <div class="row">
        <div class="col-md-10 offset-md-2">
            <table class="table">
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Gender</th>
                    <th>IsFire</th>
                    <th>操作</th>
                </tr>
                @Html.DisplayFor(p => p.Employees)
            </table>
            <a asp-page="AddEmployee" asp-route-departmentId="@ViewData["DepartmentId"]">Add</a>
        </div>
    </div>
    
    @functions{
        public class EmployeeListMode : PageModel
        {
            private readonly IEmployeesService _employeesService;
            public IEnumerable<Employee> Employees { get; set; }
    
            public EmployeeListMode(IEmployeesService employeesService)
            {
                _employeesService = employeesService;
            }
        
            public async Task OnGetAsync(int departmentId)
            {
                Employees = await _employeesService.GetByDepartmentId(departmentId);
                ViewData["DepartmentId"] = departmentId;
        
            }
        
            public async Task<IActionResult> OnGetFireAsync(int employeeId, int departmentId)
            {
                await _employeesService.Frie(employeeId);
                //int dpId = Convert.ToInt32( ViewData["DepartmentId"]);
                //return RedirectToPage("EmployeeList", new { dpId });
                return RedirectToPage("EmployeeList", new { departmentId });
        
            }
        }
    }
    
    

    要点

    带参数的Page

    @page "{departmentId:int}"
    

    @functionsPageModel

    Page中定义PageModel,使用

    @functions{
        public class EmployeeListMode : PageModel
        {
            ...
        }
      ...
    
    
    @model EmployeeListMode
    ...
      @Html.DisplayFor(p => p.Employees)
    ...
    @functions{
        public class EmployeeListMode : PageModel
        {
            ...
            public IEnumerable<Employee> Employees { get; set; }
            public async Task OnGetAsync(int departmentId)
            {
                Employees = await _employeesService.GetByDepartmentId(departmentId);
                ...
            }
          
        }
    }  
    

    OnGetAsync`获取本页面

            public async Task OnGetAsync(int departmentId)
            {
                Employees = await _employeesService.GetByDepartmentId(departmentId);
                ViewData["DepartmentId"] = departmentId;
    
            }
    

    跳转连接添加页面

     <a asp-page="AddEmployee" asp-route-departmentId="@ViewData["DepartmentId"]">Add</a>
    

    DisplayTemplates

    @Html.DisplayFor使用DisplayTemplates

    Pages/DisplayTemplates/Employee.cshtml

    @model Three.Models.Employee
    
    <tr>
        <td>@Model.FirstName</td>
        <td>@Model.LastName</td>
        <td>@Model.Gender</td>
        <td>@(Model.Fired ? "是": "")</td>
        <td>
            @if (!Model.Fired)
            {
                <a asp-page="EmployeeList"
                   asp-page-handler="Fire"
                   asp-route-employeeId="@Model.Id"
                   asp-route-departmentId="@Model.DepartmentId">Fire</a>
            }
        
        </td>
    </tr>   
    

    asp-page-handler

    ​ 其中 <a ... asp-page-handler="Fire"...>

         @functions{
            public class EmployeeListMode : PageModel
            {
                ...
                public async Task<IActionResult> OnGetFireAsync(int employeeId, int departmentId)
                {
                    await _employeesService.Frie(employeeId);
                    //int dpId = Convert.ToInt32( ViewData["DepartmentId"]);
                    //return RedirectToPage("EmployeeList", new { dpId });
                    return RedirectToPage("EmployeeList", new { departmentId });
                }
    
  • 相关阅读:
    安装node.js webkit环境[一]
    wpf 窗口最小化后,触发某事件弹出最小化窗口并置顶
    c# 旋转图片 无GDI+一般性错误
    类库里面添加日志记录 log4net
    string转xml
    DES c#加密后java解密
    使用排序字典排序
    怎么让一段xml被识别为字符串
    新装iis 页面503错误 DefaultAppPool停止解决方案
    hession
  • 原文地址:https://www.cnblogs.com/easy5weikai/p/13030649.html
Copyright © 2020-2023  润新知