Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 변수
- 코드업자바
- 코딩테스트
- 자바연산자
- C#프로그래밍
- 사용자입력
- 리터럴
- Algorithm
- 프로그래머스파이썬
- 개발입문
- Java
- 백준
- 알고리즘
- 디자인패턴
- 코드업
- 수학연산
- SWEA
- 자바클래스
- 기초프로그래밍
- 코드업100제자바
- SWEA파이썬
- C#변수
- 자바
- 코드업100제
- 제어구조
- VARIABLE
- Literal
- c#
- 백준파이썬
- Codeup
Archives
- Today
- Total
제니노트
Delete [C#] 본문
반응형
ClubController.cs
using CoreProjectPrac.Data; //DB컨텍스트
using CoreProjectPrac.Interfaces;
using CoreProjectPrac.Models;
using CoreProjectPrac.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics.Eventing.Reader;
using System.Reflection.Emit;
namespace CoreProjectPrac.Controllers
{
public class ClubController : Controller //Controller 클래스 상속
{
//주입 생성자 정의
private readonly IClubRepository _clubRepository;
private IPhotoService _photoService;
public ClubController(IClubRepository clubRepository, IPhotoService photoService) //IClubRepository 인터페이스 주입
{
_clubRepository = clubRepository;
_photoService = photoService;
}
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(CreateClubViewModel clubVM) //클럽 생성에 필요한 정보 포함하여 제출
{
if (!ModelState.IsValid) //클럽 상태가 유효하지 않을 경우
{
//이미지 업로드 시도
//업로드 수행하고 업로드 결과를 result에
var result = await _photoService.AddPhotoAsync(clubVM.Image);
var club = new Club //CreateViewModel 에서 받아온 정보와 이미지 결과를 사용하여
//클럽 객체 초기화
{
Title = clubVM.Title,
Description = clubVM.Description,
Image = result.Url.ToString(),
Address = new Address
{
Street = clubVM.Address.Street,
City = clubVM.Address.City,
State = clubVM.Address.State
}
};
_clubRepository.Add(club); //유효한 경우 클럽 정보를 DB에 추가한다.
return RedirectToAction("Index"); //저장이 끝나면 Index 메서드로 리다이렉션
}
else
{
//이미지 업로드에 실패한 경우 클라이언트에 표시
ModelState.AddModelError("", "Photo upload failed");
}
return View(clubVM); //원래의 Create 뷰로
}
public async Task<IActionResult> Edit(int id) //클럽 정보 수정
{
var club = await _clubRepository.GetByIdAsync(id);//클럽 정보 DB에서 가져오기
if (club == null) return View("Error"); //클럽 존재하지 않으면 Error 뷰 및 중단
var clubVM = new EditClubViewModel //수정 폼에 현재 정보 채우기
{
Title = club.Title,
Description = club.Description,
AddressId = club.AddressId,
Address = club.Address,
URL = club.Image,
ClubCategory = club.ClubCategory
};
return View(clubVM);
}
[HttpPost]
public async Task<IActionResult> Edit(int id, EditClubViewModel clubVM) //Post 액션 메서드
{
if (!ModelState.IsValid) //유효성 검사
{
ModelState.AddModelError("", "Faild to edit club"); //오류메시지를 모델 상태에 추가
return View("Edit", clubVM); //편집 폼 다시보여주기
}
var userClub = await _clubRepository.GetByIdAsyncNoTracking(id); //클럽 정보 가져오기
//NoTracking : 이전 정보를 가져오는 단계에서 추적이 필요하지 않으므로 DB 추적을 하지 않도록 한다.
if (userClub != null)
{
try
{
await _photoService.DeletePhotoAsync(userClub.Image); //이미지삭제
}
catch (Exception ex)
{
ModelState.AddModelError("", "Could not delete Photo");
return View(clubVM);
}
var photoResult = await _photoService.AddPhotoAsync(clubVM.Image); //새 이미지 업로드
var club = new Club //클럽객체 초기화
{
Id = id,
Title = clubVM.Title,
Description = clubVM.Description,
Image = photoResult.Url.ToString(),
AddressId = clubVM.AddressId,
Address = clubVM.Address,
};
_clubRepository.Update(club); // 데이터베이스에 클럽 정보 업데이트
return RedirectToAction("Index"); //Index로 리다이렉션
}
else //실패시
{
return View(clubVM); //원래의 편집뷰로
}
}
public async Task<IActionResult> Delete(int id) //GET요청
{
var clubDetails = await _clubRepository.GetByIdAsync(id); //Id 에 해당클럽정보를 비동기적으로 가져온다.
if (clubDetails == null) return View("Error"); //Error 뷰
return View(clubDetails); //존재하는 경우 clubDetails에 저장하고, View메서드에 전달
}
[HttpPost, ActionName("Delete")] //POST 요청
public async Task<IActionResult> DeleteClub(int id)
{
var clubDetails = await _clubRepository.GetByIdAsync(id); //id를 통해 클럽정보 받기
if (clubDetails == null) return View("Error"); //존재하지 않으면 Error
_clubRepository.Delete(clubDetails); //클럽 정보 삭제
return RedirectToAction("Index"); //Index로 리다이렉트
}
}
}
Delete.html
@using CoreProjectPrac.Data.Enum
@model Club
<!-- Club 모델 사용 -->
<h1>Are you sure you want to delete this club?</h1>
<!--HTTP POST, Delete작업-->
<form method="post" asp-action="Delete" enctype="multipart/form-data">
<!-- ID를 Post 요청으로 전달.,-->
<input type="hidden" value="AddressId" id="AddressId" />
<div class="form-group">
<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="Description">
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ClubCategory">Club Category</label>
<select asp-for="ClubCategory" asp-items="@Html.GetEnumSelectList<ClubCategory>()" class="form-control">
<option selected="selected" value="">--Select--</option>
</select>
<span asp-validation-for="ClubCategory" class="text-danger"></span>
</div>
<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.Street" 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="Street">
<span asp-validation-for="Address.State" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Image">Image</label>
<input asp-for="Image" type="file" class="form-control" placeholder="Image">
<span asp-validation-for="Image" class="text-danger"></span>
</div>
</form>
<div class="form-group">
<form action="Delete" method="post">
<input type="hidden" asp-for="Id" />
<!-- DeleteClub액션 메서드로 POST 요청이 전송 -->
<input type="submit" value="Confirm" class="btn btn-danger float-right mt-3" />
</form>
</div>
반응형
'C# > C#' 카테고리의 다른 글
C#로 간단한 콘솔 애플리케이션 만들기 [C#] (0) | 2023.10.11 |
---|---|
변수와 데이터 형식 변환(Type Conversion) [C#] (1) | 2023.10.10 |
Edit [C#] (0) | 2023.09.25 |
CREATE [C#] (0) | 2023.09.25 |
DI, Repository Pattern [C#] (0) | 2023.09.25 |
Comments