■ 스캐폴딩 기능을 사용해 RAZOR 페이지 웹앱을 만드는 방법을 보여준다. (최종)
▶ Models/Movie.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TestProject.Models { /// <summary> /// 영화 /// </summary> public class Movie { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> [Required] [StringLength(60, MinimumLength = 3)] public string Title { get; set; } #endregion #region 릴리즈 일자 - ReleaseDate /// <summary> /// 릴리즈 일자 /// </summary> [DataType(DataType.Date)] [Display(Name = "Release Date")] public DateTime ReleaseDate { get; set; } #endregion #region 장르 - Genre /// <summary> /// 장르 /// </summary> [Required] [StringLength(30)] public string Genre { get; set; } #endregion #region 가격 - Price /// <summary> /// 가격 /// </summary> [DataType(DataType.Currency)] [Column(TypeName = "decimal(18, 2)")] [Range(1, 100)] public decimal Price { get; set; } #endregion #region 등급 - Rating /// <summary> /// 등급 /// </summary> [Required] [StringLength(5)] [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$")] public string Rating { get; set; } #endregion } } |
▶ Models/MovieData.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; using TestProject.Data; namespace TestProject.Models { /// <summary> /// 영화 데이터 /// </summary> public static class MovieData { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 초기화하기 - Initialize(serviceProvider) /// <summary> /// 초기화하기 /// </summary> /// <param name="serviceProvider">서비스 제공자</param> public static void Initialize(IServiceProvider serviceProvider) { using(var context = new DatabaseContext(serviceProvider.GetRequiredService<DbContextOptions<DatabaseContext>>())) { if(context.Movie.Any()) { return; } context.Movie.AddRange ( new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-2-12"), Genre = "Romantic Comedy", Price = 7.99M, Rating = "R" }, new Movie { Title = "Ghostbusters ", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M, Rating = "R" }, new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M, Rating = "R" }, new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M, Rating = "R" } ); context.SaveChanges(); } } #endregion } } |
▶ Data/DatabaseContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using Microsoft.EntityFrameworkCore; using TestProject.Models; namespace TestProject.Data { /// <summary> /// 데이터베이스 컨텍스트 /// </summary> public class DatabaseContext : DbContext { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 영화 - Movie /// <summary> /// 영화 /// </summary> public DbSet<Movie> Movie { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DatabaseContext(options) /// <summary> /// 생성자 /// </summary> /// <param name="options">옵션</param> public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { } #endregion } } |
▶ appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
{ "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*", "ConnectionStrings" : { "DefaultConnection" : "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True;" } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using TestProject.Data; namespace TestProject { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DatabaseContext> ( options => { options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); } ); services.AddRazorPages(); } #endregion #region 구성하기 - Configure(app, environment) /// <summary> /// 구성하기 /// </summary> /// <param name="app">애플리케이션 빌더</param> /// <param name="environment">웹 호스트 환경</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { if(environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using TestProject.Models; namespace TestProject { /// <summary> /// 프로그램 /// </summary> public class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 프로그램 시작하기 - Main(argumentArray) /// <summary> /// 프로그램 시작하기 /// </summary> /// <param name="argumentArray">인자 배열</param> public static void Main(string[] argumentArray) { IHost host = CreateHostBuilder(argumentArray).Build(); using(IServiceScope scope = host.Services.CreateScope()) { IServiceProvider serviceProvider = scope.ServiceProvider; try { MovieData.Initialize(serviceProvider); } catch(Exception exception) { ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>(); logger.LogError(exception, "데이터베이스에 데이터 추가시 에러가 발생했습니다."); } } host.Run(); } #endregion #region 호스트 빌더 생성하기 - CreateHostBuilder(argumentArray) /// <summary> /// 호스트 빌더 생성하기 /// </summary> /// <param name="argumentArray">인자 배열</param> /// <returns>호스트 빌더</returns> public static IHostBuilder CreateHostBuilder(string[] argumentArray) => Host.CreateDefaultBuilder(argumentArray) .ConfigureWebHostDefaults ( builder => { builder.UseStartup<Startup>(); } ); #endregion } } |
▶ Pages/Movies/Index.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
@page @using TestProject.Models @model TestProject.Pages.Movies.IndexModel @{ ViewData["Title"] = "Index"; } <h1>Index</h1> <p> <a asp-page="Create">Create New</a> </p> <form> <p> <select asp-for="MovieGenre" asp-items="Model.GenreSelectList"> <option value="">All</option> </select> Title : <input type="text" asp-for="SearchString" /> <input type="submit" value="Filter" /> </p> </form> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.MovieList[0].Title) </th> <th> @Html.DisplayNameFor(model => model.MovieList[0].ReleaseDate) </th> <th> @Html.DisplayNameFor(model => model.MovieList[0].Genre) </th> <th> @Html.DisplayNameFor(model => model.MovieList[0].Price) </th> <th> @Html.DisplayNameFor(model => model.MovieList[0].Rating) </th> <th></th> </tr> </thead> <tbody> @foreach(Movie movie in Model.MovieList) { <tr> <td> @Html.DisplayFor(modelItem => movie.Title) </td> <td> @Html.DisplayFor(modelItem => movie.ReleaseDate) </td> <td> @Html.DisplayFor(modelItem => movie.Genre) </td> <td> @Html.DisplayFor(modelItem => movie.Price) </td> <td> @Html.DisplayFor(modelItem => movie.Rating) </td> <td> <a asp-page="./Edit" asp-route-id="@movie.ID">Edit</a> | <a asp-page="./Details" asp-route-id="@movie.ID">Details</a> | <a asp-page="./Delete" asp-route-id="@movie.ID">Delete</a> </td> </tr> } </tbody> </table> |
▶ Pages/Movies/Index.cshtml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TestProject.Data; using TestProject.Models; namespace TestProject.Pages.Movies { /// <summary> /// 인덱스 모델 /// </summary> public class IndexModel : PageModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 컨텍스트 /// </summary> private readonly DatabaseContext context; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 영화 리스트 - MovieList /// <summary> /// 영화 리스트 /// </summary> public IList<Movie> MovieList { get;set; } #endregion #region 검색 문자열 - SearchString /// <summary> /// 검색 문자열 /// </summary> [BindProperty(SupportsGet = true)] public string SearchString { get; set; } #endregion #region 장르 선택 리스트 - GenreSelectList /// <summary> /// 장르 선택 리스트 /// </summary> public SelectList GenreSelectList { get; set; } #endregion #region 영화 장르 - MovieGenre /// <summary> /// 영화 장르 /// </summary> [BindProperty(SupportsGet = true)] public string MovieGenre { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - IndexModel(context) /// <summary> /// 생성자 /// </summary> /// <param name="context">컨텍스트</param> public IndexModel(DatabaseContext context) { this.context = context; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region GET 비동기 처리하기 - OnGetAsync() /// <summary> /// GET 비동기 처리하기 /// </summary> /// <returns>태스크</returns> public async Task OnGetAsync() { var genreQueryable = from movie in this.context.Movie orderby movie.Genre select movie.Genre; var movieQueryable = from movie in this.context.Movie select movie; if(!string.IsNullOrEmpty(SearchString)) { movieQueryable = movieQueryable.Where(s => s.Title.Contains(SearchString)); } if(!string.IsNullOrEmpty(MovieGenre)) { movieQueryable = movieQueryable.Where(x => x.Genre == MovieGenre); } GenreSelectList = new SelectList(await genreQueryable.Distinct().ToListAsync()); MovieList = await movieQueryable.ToListAsync(); } #endregion } } |
▶ Pages/Movies/Create.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
@page @model TestProject.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"> <label asp-for="Movie.Rating" class="control-label"></label> <input asp-for="Movie.Rating" class="form-control" /> <span asp-validation-for="Movie.Rating" 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");} } |
▶ Pages/Movies/Create.cshtml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.Threading.Tasks; using TestProject.Data; using TestProject.Models; namespace TestProject.Pages.Movies { /// <summary> /// 생성 모델 /// </summary> public class CreateModel : PageModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 컨텍스트 /// </summary> private readonly DatabaseContext context; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 영화 - Movie /// <summary> /// 영화 /// </summary> [BindProperty] public Movie Movie { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - CreateModel(context) /// <summary> /// 생성자 /// </summary> /// <param name="context">컨텍스트</param> public CreateModel(DatabaseContext context) { this.context = context; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region GET 처리하기 - OnGet() /// <summary> /// GET 처리하기 /// </summary> /// <returns>액션 결과</returns> public IActionResult OnGet() { return Page(); } #endregion #region POST 비동기 처리하기 - OnPostAsync() /// <summary> /// POST 비동기 처리하기 /// </summary> /// <returns>액션 결과 태스크</returns> public async Task<IActionResult> OnPostAsync() { if(!ModelState.IsValid) { return Page(); } this.context.Movie.Add(Movie); await this.context.SaveChangesAsync(); return RedirectToPage("./Index"); } #endregion } } |
▶ Pages/Movies/Edit.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
@page "{id:int}" @model TestProject.Pages.Movies.EditModel @{ ViewData["Title"] = "Edit"; } <h1>Edit</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> <input type="hidden" asp-for="Movie.ID" /> <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"> <label asp-for="Movie.Rating" class="control-label"></label> <input asp-for="Movie.Rating" class="form-control" /> <span asp-validation-for="Movie.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-page="./Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } |
▶ Pages/Movies/Edit.cshtml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading.Tasks; using TestProject.Data; using TestProject.Models; namespace TestProject.Pages.Movies { /// <summary> /// 편집 모델 /// </summary> public class EditModel : PageModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 컨텍스트 /// </summary> private readonly DatabaseContext context; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 영화 - Movie /// <summary> /// 영화 /// </summary> [BindProperty] public Movie Movie { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - EditModel(context) /// <summary> /// 생성자 /// </summary> /// <param name="context">컨텍스트</param> public EditModel(DatabaseContext context) { this.context = context; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region GET 비동기 처리하기 - OnGetAsync(id) /// <summary> /// GET 비동기 처리하기 /// </summary> /// <param name="id">ID</param> /// <returns>액션 결과 태스크</returns> public async Task<IActionResult> OnGetAsync(int id) { Movie = await this.context.Movie.FirstOrDefaultAsync(m => m.ID == id); if(Movie == null) { return NotFound(); } return Page(); } #endregion #region POST 비동기 처리하기 - OnPostAsync() /// <summary> /// POST 비동기 처리하기 /// </summary> /// <returns>액션 결과 태스크</returns> public async Task<IActionResult> OnPostAsync() { if(!ModelState.IsValid) { return Page(); } this.context.Attach(Movie).State = EntityState.Modified; try { await this.context.SaveChangesAsync(); } catch(DbUpdateConcurrencyException) { if(!MovieExists(Movie.ID)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 영화 존재 여부 구하기 - MovieExists(id) /// <summary> /// 영화 존재 여부 구하기 /// </summary> /// <param name="id">ID</param> /// <returns>영화 존재 여부</returns> private bool MovieExists(int id) { return this.context.Movie.Any(e => e.ID == id); } #endregion } } |
▶ Pages/Movies/Delete.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
@page "{id:int}" @model TestProject.Pages.Movies.DeleteModel @{ 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.Movie.Title) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.Title) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.ReleaseDate) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.ReleaseDate) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.Genre) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.Genre) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.Price) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.Price) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.Rating) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.Rating) </dd> </dl> <form method="post"> <input type="hidden" asp-for="Movie.ID" /> <input type="submit" value="Delete" class="btn btn-danger" /> | <a asp-page="./Index">Back to List</a> </form> </div> |
▶ Pages/Movies/Delete.cshtml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using TestProject.Data; using TestProject.Models; namespace TestProject.Pages.Movies { /// <summary> /// 삭제 모델 /// </summary> public class DeleteModel : PageModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 컨텍스트 /// </summary> private readonly DatabaseContext context; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 영화 - Movie /// <summary> /// 영화 /// </summary> [BindProperty] public Movie Movie { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DeleteModel(context) /// <summary> /// 생성자 /// </summary> /// <param name="context">컨텍스트</param> public DeleteModel(DatabaseContext context) { this.context = context; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region GET 비동기 처리하기 - OnGetAsync(id) /// <summary> /// GET 비동기 처리하기 /// </summary> /// <param name="id">ID</param> /// <returns>액션 결과 태스크</returns> public async Task<IActionResult> OnGetAsync(int id) { Movie = await this.context.Movie.FirstOrDefaultAsync(m => m.ID == id); if(Movie == null) { return NotFound(); } return Page(); } #endregion #region POST 비동기 처리하기 - OnPostAsync(id) /// <summary> /// POST 비동기 처리하기 /// </summary> /// <param name="id">ID</param> /// <returns>액션 결과 태스크</returns> public async Task<IActionResult> OnPostAsync(int id) { Movie = await this.context.Movie.FindAsync(id); if(Movie != null) { this.context.Movie.Remove(Movie); await this.context.SaveChangesAsync(); } return RedirectToPage("./Index"); } #endregion } } |
▶ Pages/Movies/Details.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
@page "{id:int}" @model TestProject.Pages.Movies.DetailsModel @{ ViewData["Title"] = "Details"; } <h1>Details</h1> <div> <h4>Movie</h4> <hr /> <dl class="row"> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.Title) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.Title) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.ReleaseDate) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.ReleaseDate) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.Genre) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.Genre) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.Price) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.Price) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Movie.Rating) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Movie.Rating) </dd> </dl> </div> <div> <a asp-page="./Edit" asp-route-id="@Model.Movie.ID">Edit</a> | <a asp-page="./Index">Back to List</a> </div> |
▶ Pages/Movies/Details.cshtml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using TestProject.Data; using TestProject.Models; namespace TestProject.Pages.Movies { /// <summary> /// 상세 모델 /// </summary> public class DetailsModel : PageModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 컨텍스트 /// </summary> private readonly DatabaseContext context; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 영화 - Movie /// <summary> /// 영화 /// </summary> [BindProperty] public Movie Movie { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DetailsModel(context) /// <summary> /// 생성자 /// </summary> /// <param name="context">컨텍스트</param> public DetailsModel(DatabaseContext context) { this.context = context; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region GET 비동기 처리하기 - OnGetAsync(id) /// <summary> /// GET 비동기 처리하기 /// </summary> /// <param name="id">ID</param> /// <returns>액션 결과 태스크</returns> public async Task<IActionResult> OnGetAsync(int id) { Movie = await context.Movie.FirstOrDefaultAsync(m => m.ID == id); if(Movie == null) { return NotFound(); } return Page(); } #endregion } } |
※ TestDB 데이터베이스 생성
1. 비주얼 스튜디오를 실행한다.
2. 비주얼 스튜디오에서 [보기] / [SQL Server 개체 탐색기] 메뉴를 클릭한다.
3. [SQL Server 개체 탐색기]에서 [SQL Server] / [(localdb)MSSQLLocalDB…] / [데이터베이스] 노드 위에서 마우스 오른쪽 버튼을 클릭한다.
4. 컨텍스트 메뉴에서 [새 데이터베이스 추가] 메뉴를 클릭한다.
5. [데이터베이스 만들기] 대화 상자에서 아래와 같이 입력하고 [확인] 버튼을 클릭한다.
6. 비주얼 스튜디오에서 [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 클릭한다.
7. [패키지 관리자 콘솔]에서 아래 명령을 실행한다.
▶ 실행 명령
1 2 3 |
Update-Database |