MVC Core CURD
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.Rendering; 7 using Microsoft.EntityFrameworkCore; 8 using MvcMovie.Data; 9 using MvcMovie.Models; 10 11 namespace MvcMovie.Controllers 12 { 13 public class MoviesController : Controller 14 { 15 private readonly MvcMovieContext _context; 16 17 public MoviesController(MvcMovieContext context) 18 { 19 _context = context; 20 } 21 22 // GET: Movies 23 public async Task<IActionResult> Index(string movieGenre, string searchString) 24 { 25 if (_context.Movie == null) 26 { 27 return Problem("没有设置数据库上下文实体"); 28 } 29 IQueryable<string> genreQuery = from m in _context.Movie orderby m.Genre select m.Genre; 30 var movies = from m in _context.Movie select m; 31 if (!string.IsNullOrEmpty(searchString)) 32 { 33 movies = movies.Where(m => m.Title!.Contains(searchString)); 34 } 35 if (!string.IsNullOrEmpty(movieGenre)) 36 { 37 movies = movies.Where(m => m.Genre == movieGenre); 38 } 39 var movieGenreVM = new MovieGenreViewModel 40 { 41 Genres = new SelectList(await genreQuery.Distinct().ToListAsync()), 42 Movies = await movies.ToListAsync(), 43 }; 44 return View(movieGenreVM); 45 } 46 47 // GET: Movies/Details/5 48 public async Task<IActionResult> Details(int? id) 49 { 50 if (id == null || _context.Movie == null) 51 { 52 return NotFound(); 53 } 54 55 var movie = await _context.Movie 56 .FirstOrDefaultAsync(m => m.Id == id); 57 if (movie == null) 58 { 59 return NotFound(); 60 } 61 62 return View(movie); 63 } 64 65 // GET: Movies/Create 66 public IActionResult Create() 67 { 68 return View(); 69 } 70 71 // POST: Movies/Create 72 // To protect from overposting attacks, enable the specific properties you want to bind to. 73 // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. 74 [HttpPost] 75 [ValidateAntiForgeryToken] 76 public async Task<IActionResult> Create( Movie movie) 77 { 78 if (ModelState.IsValid) 79 { 80 _context.Add(movie); 81 await _context.SaveChangesAsync(); 82 return RedirectToAction(nameof(Index)); 83 } 84 return View(movie); 85 } 86 87 // GET: Movies/Edit/5 88 public async Task<IActionResult> Edit(int? id) 89 { 90 if (id == null || _context.Movie == null) 91 { 92 return NotFound(); 93 } 94 95 var movie = await _context.Movie.FindAsync(id); 96 if (movie == null) 97 { 98 return NotFound(); 99 } 100 return View(movie); 101 } 102 103 // POST: Movies/Edit/5 104 // To protect from overposting attacks, enable the specific properties you want to bind to. 105 // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. 106 [HttpPost] 107 [ValidateAntiForgeryToken] 108 public async Task<IActionResult> Edit(int id, [Bind("Id,Title,Date,ReleaseDate,Genre,Price,Rating")] Movie movie) 109 { 110 if (id != movie.Id) 111 { 112 return NotFound(); 113 } 114 115 if (ModelState.IsValid) 116 { 117 try 118 { 119 _context.Update(movie); 120 await _context.SaveChangesAsync(); 121 } 122 catch (DbUpdateConcurrencyException) 123 { 124 if (!MovieExists(movie.Id)) 125 { 126 return NotFound(); 127 } 128 else 129 { 130 throw; 131 } 132 } 133 return RedirectToAction(nameof(Index)); 134 } 135 return View(movie); 136 } 137 138 // GET: Movies/Delete/5 139 public async Task<IActionResult> Delete(int? id) 140 { 141 if (id == null || _context.Movie == null) 142 { 143 return NotFound(); 144 } 145 146 var movie = await _context.Movie 147 .FirstOrDefaultAsync(m => m.Id == id); 148 if (movie == null) 149 { 150 return NotFound(); 151 } 152 153 return View(movie); 154 } 155 156 // POST: Movies/Delete/5 157 [HttpPost, ActionName("Delete")] 158 [ValidateAntiForgeryToken] 159 public async Task<IActionResult> DeleteConfirmed(int id) 160 { 161 if (_context.Movie == null) 162 { 163 return Problem("Entity set 'MvcMovieContext.Movie' is null."); 164 } 165 var movie = await _context.Movie.FindAsync(id); 166 if (movie != null) 167 { 168 _context.Movie.Remove(movie); 169 } 170 171 await _context.SaveChangesAsync(); 172 return RedirectToAction(nameof(Index)); 173 } 174 175 private bool MovieExists(int id) 176 { 177 return (_context.Movie?.Any(e => e.Id == id)).GetValueOrDefault(); 178 } 179 } 180 }
1 using System.ComponentModel.DataAnnotations; 2 using System.ComponentModel.DataAnnotations.Schema; 3 4 namespace MvcMovie.Models 5 { 6 public class Movie 7 { 8 public int Id { get; set; } 9 [StringLength(60,MinimumLength =3)] 10 [Required] 11 public string? Title { get; set; } 12 [Display(Name ="Release Date")] 13 [DataType(DataType.Date)] 14 public DateTime ReleaseDate { get; set; } 15 [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$")] 16 [Required] 17 [StringLength(30)] 18 public string? Genre { get; set; } 19 [Range(1,100)] 20 public decimal Price { get; set; } 21 [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$")] 22 [StringLength(5)] 23 [Required] 24 public string? Rating { get; set; } 25 } 26 }
1 using Microsoft.AspNetCore.Mvc.Rendering; 2 3 namespace MvcMovie.Models 4 { 5 /// <summary> 6 /// 电影流派 7 /// </summary> 8 public class MovieGenreViewModel 9 { 10 public List<Movie>? Movies { get; set; } 11 public SelectList? Genres { get; set; } 12 public string? MovieGenre { get; set; } 13 public string? SearchString { get; set; } 14 } 15 }
@model MvcMovie.Models.Movie @{ ViewData["Title"] = "Create"; } <h1>Create</h1> <h4>Movie</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Title" class="control-label"></label> <input asp-for="Title" class="form-control" /> <span asp-validation-for="Title" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="ReleaseDate" class="control-label"></label> <input asp-for="ReleaseDate" class="form-control" /> <span asp-validation-for="ReleaseDate" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Genre" class="control-label"></label> <input asp-for="Genre" class="form-control" /> <span asp-validation-for="Genre" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Price" class="control-label"></label> <input asp-for="Price" class="form-control" /> <span asp-validation-for="Price" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Rating" class="control-label"></label> <input asp-for="Rating" class="form-control"/> <span asp-validation-for="Rating" class="text-danger"></span> </div> <br/> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
@model MvcMovie.Models.Movie @{ ViewData["Title"] = "Delete"; } <h1>Delete</h1> <h3>Are you sure you want to delete this?</h3> <div> <h4>Movie</h4> <hr /> <dl class="row"> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.Title) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.Title) </dd> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.ReleaseDate) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.ReleaseDate) </dd> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.Genre) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.Genre) </dd> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.Price) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.Price) </dd> </dl> <form asp-action="Delete"> <input type="hidden" asp-for="Id" /> <input type="submit" value="Delete" class="btn btn-danger" /> | <a asp-action="Index">Back to List</a> </form> </div>
@model MvcMovie.Models.Movie @{ ViewData["Title"] = "Details"; } <h1>Details</h1> <div> <h4>Movie</h4> <hr /> <dl class="row"> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.Title) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.Title) </dd> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.ReleaseDate) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.ReleaseDate) </dd> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.Genre) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.Genre) </dd> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.Price) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.Price) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model=>model.Rating) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model=>model.Rating) </dd> </dl> </div> <div> <a asp-action="Edit" asp-route-id="@Model?.Id">Edit</a> | <a asp-action="Index">Back to List</a> </div>
@model MvcMovie.Models.Movie @{ ViewData["Title"] = "Edit"; } <h1>Edit</h1> <h4>Movie</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Edit"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <input type="hidden" asp-for="Id" /> <div class="form-group"> <label asp-for="Title" class="control-label"></label> <input asp-for="Title" class="form-control" /> <span asp-validation-for="Title" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="ReleaseDate" class="control-label"></label> <input asp-for="ReleaseDate" class="form-control" /> <span asp-validation-for="ReleaseDate" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Genre" class="control-label"></label> <input asp-for="Genre" class="form-control" /> <span asp-validation-for="Genre" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Price" class="control-label"></label> <input asp-for="Price" class="form-control" /> <span asp-validation-for="Price" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Rating" class="control-label"></label> <input asp-for="Rating" class="form-control"/> <span asp-validation-for="Rating" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Save" class="btn btn-primary" /> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
@model MvcMovie.Models.MovieGenreViewModel @{ ViewData["Title"] = "Index"; } <h1>Index</h1> <form asp-controller="Movies" asp-action="Index" method="get"> <p> <select asp-for="MovieGenre" asp-items="Model.Genres"> <option value="">All</option> </select> Title: <input type="text" name="SearchString" /> <input type="submit" value="查询" /> </p> </form> <p> <a asp-action="Create">Create New</a> </p> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Movies!.First().Title) </th> <th> @Html.DisplayNameFor(model => model.Movies!.First().ReleaseDate) </th> <th> @Html.DisplayNameFor(model => model.Movies!.First().Genre) </th> <th> @Html.DisplayNameFor(model => model.Movies!.First().Price) </th> <th> @Html.DisplayNameFor(model=>model.Movies!.First().Rating) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model.Movies!) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.ReleaseDate) </td> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.DisplayFor(modelItem=>item.Rating) </td> <td> <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> | <a asp-action="Details" asp-route-id="@item.Id">Details</a> | <a asp-action="Delete" asp-route-id="@item.Id">Delete</a> @Html.ActionLink("查看详情","Details",new{Id=item.Id}) </td> </tr> } </tbody> </table>