제니노트

CREATE [C#] 본문

C#/C#

CREATE [C#]

yangjennie 2023. 9. 25. 08:10
반응형

Create.cshtml

<!-- ClubCategory 열거형을 사용하기 위해 네임스페이스 가져오기-->
@using CoreProjectPrac.Data.Enum; 
@model Club //Club 모델 클래스가 뷰의 모델 
@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

<!-- 서버 제출 시 POST 요청, Create는 양식이 서버로 제출될 때 호출할 액션 메서드 -->
<form method="post" asp-action="Create">
    <div class="form-group">
        <!-- asp-for : 입력 필드와 모델 속성을 자동으로 연결-->
        <label asp-for="Title">Title</label>
        <input asp-for="Title" class="form-control" placeholder="Title">
        <!-- 유효성 검사 -->
        <span asp-validation-for="Title" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Description">Description</label>
        <input asp-for="Description" class="form-control" placeholder="Descrpition">
        <span asp-validation-for="Description" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Image">Image</label>
        <input asp-for="Image" class="form-control" placeholder="Image">
        <span asp-validation-for="Image" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="ClubCategory">ClubCategory</label>
        <select asp-for="ClubCategory" asp-items="@Html.GetEnumSelectList<ClubCategory>()" class="form-control form-control-lg">
            <option>--Select--</option>
        </select>
        <span asp-validation-for="ClubCategory" class="text-danger"></span>
    </div>
    <!-- Street, City, State 입력 필드 -->
    <div class="form-group">
        <label asp-for="Address.Street">Street</label>
        <input asp-for="Address.Street" class="form-control" placeholder="Street">
        <span asp-validation-for="Address.Street" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Address.City">City</label>
        <input asp-for="Address.City" class="form-control" placeholder="City">
        <span asp-validation-for="Address.City" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Address.State">State</label>
        <input asp-for="Address.State" class="form-control" placeholder="State">
        <span asp-validation-for="Address.State" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

 

asp-for 을 사용하여 HTML 입력 요소와 서버 측 모델 속성을 쉽게 연결했다.

사용자가 입력한 데이터를 서버로 전송하고 처리하는데 유용하다.

(입력 데이터가 모델 속성에 자동으로 연결됨)

 

ClubController.cs

using CoreProjectPrac.Data; //DB컨텍스트
using CoreProjectPrac.Interfaces;
using CoreProjectPrac.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace CoreProjectPrac.Controllers
{
    public class ClubController : Controller //Controller 클래스 상속 
    {

        private readonly IClubRepository _clubRepository;
        public ClubController(IClubRepository clubRepository) //IClubRepository 인터페이스 주입
        {

            _clubRepository = clubRepository; 
        }
        public async Task<IActionResult> Index()  //사용자의 요청을 처리, 인덱스 뷰를 반환 C 

        {
            IEnumerable<Club> clubs = await _clubRepository.GetAll();  //M 모든 클럽 정보 반환 
            //clubs 테이블의 모든 레코드를 가져와서 저장 
            return View(clubs); //V  
        }


        public async Task<IActionResult> Detail(int id) //상세정보 
        {

            Club club = await _clubRepository.GetByIdAsync(id);  //클럽정보 id를 통해 가져오기 
            return View(club);
        }

        public IActionResult Create() //클럽 생성뷰
            //IActionResult : 액션 메서드가 다양한 결과를 반환할 수 있도록 하는 인터페이스 
        {
            return View(); //HTML 페이지 표시, ViewResult 반환 
        }

        [HttpPost]
        public async Task<IActionResult> Create(Club club) //클럽 정보 입력하고 제출
        {
            if (!ModelState.IsValid) //클럽 정보가 유효하지 않을 경우 
            {
                return View(club); 
            }
            _clubRepository.Add(club); //유효한 경우 클럽 정보를 DB에 추가한다. 
            return RedirectToAction("Index"); //저장이 끝나면 Index 메서드로 리다이렉션
        }
    }
}

 

두개의 Create() 함수는 HTTP 요청 방식에 따라 동작이 다르다.

오버로드된 메서드로, HTTP 요청 방식에 따라 어떤 액션 메서드가 호출될지 결정된다.

public IActionResult Create() 는 HTTP GET 요청에 응답한다.

/Create URL 을 요청할 때(GET) 이 액션 메서드가 호출된다.

 

아래의 액션메서드는 HTTP POST 요청에 응답한다.

클럽 생성 폼을 작성하고 제출할 때 이 액션 메서드가 호출된다. 

 

반응형

'C# > C#' 카테고리의 다른 글

Delete [C#]  (0) 2023.09.25
Edit [C#]  (0) 2023.09.25
DI, Repository Pattern [C#]  (0) 2023.09.25
Detail View 만들기 [C#]  (0) 2023.09.25
View [C#]  (0) 2023.09.25
Comments