첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
본 블로그는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 블로그 콘텐츠 향상을 위해 쓰여집니다.

728x90
반응형
728x170

TestProject.zip
다운로드

▶ Pages/Movies/Edit.cshtml

@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">
                <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");}
}

 

728x90

 

▶ Pages/Movies/Edit.cshtml.cs

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
    }
}

 

300x250

 

▶ Pages/Movies/Delete.cshtml

@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>
    </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

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

@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>
    </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

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. [패키지 관리자 콘솔]에서 아래 명령을 실행한다.

Update-Database
728x90
반응형
그리드형
Posted by 사용자 icodebroker

댓글을 달아 주세요