在 ASP.NET Core 中向 Razor Pages 实现添加数据
1、创建添加代码
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using RazorPagesMovie.Models; using System; using System.Threading.Tasks; namespace RazorPagesMovie.Pages.Movies { public class CreateModel : PageModel { private readonly RazorPagesMovie.Data.RazorPagesMovieContext _context; public CreateModel(RazorPagesMovie.Data.RazorPagesMovieContext context) { _context = context; } public IActionResult OnGet() { return Page(); } [BindProperty] public Movie Movie { get; set; } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Movie.Add(Movie); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } } }
2、实现前端页面
@page @model RazorPagesMovie.Pages.Movies.CreateModel @{ ViewData["Title"] = "Create"; } <h1>Create</h1> <h4>Movie</h4> <hr /> <div class="row"> <div class="col-md-4"> <form method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Movie.Title" class="control-label"></label> <input asp-for="Movie.Title" class="form-control" /> <span asp-validation-for="Movie.Title" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Movie.ReleaseDate" class="control-label"></label> <input asp-for="Movie.ReleaseDate" class="form-control" /> <span asp-validation-for="Movie.ReleaseDate" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Movie.Genre" class="control-label"></label> <input asp-for="Movie.Genre" class="form-control" /> <span asp-validation-for="Movie.Genre" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Movie.Price" class="control-label"></label> <input asp-for="Movie.Price" class="form-control" /> <span asp-validation-for="Movie.Price" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> <div> <a asp-page="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
核心要素:
1、public IActionResult OnGet() { return Page(); } 返回当前的默认页面
2、if (!ModelState.IsValid) { return Page(); } 模型是否验证成果;
<form method="post"> POST回调
<div asp-validation-summary="ModelOnly" class="text-danger"></div> 在网页上显示验证信息和标记
<label asp-for="Movie.Title" class="control-label"></label> 生成标签描述和
Title
属性的for
特性<input asp-for="Movie.Title" class="form-control" /> 使用 DataAnnotations 属性并在客户端生成 jQuery 验证所需的 HTML 属性。
<span asp-validation-for="Movie.Title" class="text-danger"></span> 显示错误的div和信息。