ASP.NET Core MVC에서 추가 및 수정 기능을 통해 데이터를 페이지에 전달하는 방법

LINQ 쿼리 문법과 데이터 처리

쿼리 연산자 중 주요 메서드는 다음과 같습니다:

  • First(): 조건에 맞는 첫 번째 요소를 반환하며, 없으면 예외 발생.
  • FirstOrDefault(): 조건에 맞는 첫 번째 요소를 반환하거나 없으면 null 반환.
  • Single(): 정확히 하나의 요소가 존재해야 하며, 그렇지 않으면 예외 발생.
  • SingleOrDefault(): 하나만 존재하거나 없을 수 있으며, 없으면 null 반환.
  • Where(): 조건을 만족하는 모든 요소를 필터링. 예: x.Score >= 80 && x.Sex == 1
  • Select(): 새로운 형식의 객체로 변환하여 새로운 컬렉션 생성. 예: new { x.Id, x.Score }

새 항목 추가 및 수정 시 데이터 전달 방식

1. 추가 페이지 (Increase.cshtml) 구성

@model Blog.Models.Blogs

<h2>새 글 작성</h2>
<form asp-controller="Blogs" asp-action="Increase" method="post">
    <label>제목: <input asp-for="Title" /></label><br />
    <label>내용: <input asp-for="Content" /></label><br />
    <label>작성자: <input asp-for="Author" /></label><br />
    <button type="submit">저장</button>
</form>

2. 컨트롤러 메서드 구현 (BlogsController.cs)

[HttpGet]
public IActionResult Increase()
{
    return View();
}

[HttpPost]
public IActionResult Increase(Blogs input)
{
    // 입력값 검증 (예: 빈 값 여부, 제목 중복 등)
    if (string.IsNullOrWhiteSpace(input.Title) || 
        string.IsNullOrWhiteSpace(input.Content) ||
        string.IsNullOrWhiteSpace(input.Author))
    {
        return View(input); // 유효성 실패 시 다시 표시
    }

    // 최대 ID를 조회하고, 다음 순번으로 설정
    var maxId = Db.Blogs.Select(b => b.Id).DefaultIfEmpty(0).Max();
    input.Id = maxId + 1;

    // 데이터베이스에 추가
    Db.Blogs.Add(input);

    // 성공 시 목록 페이지로 리디렉션
    return RedirectToAction("Index");
}

3. 수정 기능 구현

[HttpGet]
public IActionResult Redact(int id)
{
    var blog = Db.Blogs.FirstOrDefault(b => b.Id == id);
    return View(blog);
}

[HttpPost]
public IActionResult Redact(Blogs input)
{
    var existingBlog = Db.Blogs.FirstOrDefault(b => b.Id == input.Id);
    if (existingBlog != null)
    {
        existingBlog.Title = input.Title;
        existingBlog.Content = input.Content;
        existingBlog.Author = input.Author;
    }

    return RedirectToAction("Index");
}

4. 목록 표시 페이지 (Index.cshtml)

<link rel="stylesheet" href="~/css/base.css" />
@model List<Blog.Models.Blogs>

<a asp-action="Increase">글 추가</a>
<table>
    <tr>
        <th>ID</th>
        <th>제목</th>
        <th>내용</th>
        <th>작성자</th>
        <th>관리</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Id</td>
            <td>@item.Title</td>
            <td>@item.Content</td>
            <td>@item.Author</td>
            <td>
                <a asp-action="Redact" asp-route-id="@item.Id">수정</a>
                <a asp-action="Delete" asp-route-id="@item.Id">삭제</a>
            </td>
        </tr>
    }
</table>

5. 수정 페이지 (Redact.cshtml)

@model Blog.Models.Blogs

<h2>글 수정</h2>
<form asp-controller="Blogs" asp-action="Redact" method="post">
    <label>ID: <input asp-for="Id" readonly /></label><br />
    <label>제목: <input asp-for="Title" /></label><br />
    <label>내용: <input asp-for="Content" /></label><br />
    <label>작성자: <input asp-for="Author" /></label><br />
    <button type="submit">저장</button>
</form>

이 구조는 단순한 폼 전송을 넘어, 데이터 검증, 중복 확인, 자동 번호 부여, 성공 후 리디렉션 등의 비즈니스 로직을 포함합니다. 실제 애플리케이션에서는 더 많은 검증 및 예외 처리가 필요할 수 있습니다.

태그: ASP.NET Core MVC LINQ Controller View

5월 24일 06:27에 게시됨