Models/BoardModel.cs
게시글 데이터를 저장할 클래스
namespace MvcJqueryDemo.Models
{
public class BoardModel
{
public int Id { get; set; }
public string Title { get; set; } = "";
public string Writer { get; set; } = "";
public string Content { get; set; } = "";
public DateTime RegDate { get; set; }
}
}
각 필드의 의미
Controllers/BoardController.cs
이번에는 AJAX 요청을 처리하는 Controller를 별도로 만든다.
using Microsoft.AspNetCore.Mvc;
using MvcJqueryDemo.Models;
namespace MvcJqueryDemo.Controllers
{
public class BoardController : Controller
{
// 임시 데이터 저장소
private static List<BoardModel> boards = new()
{
new BoardModel
{
Id = 1,
Title = "첫 번째 게시글",
Writer = "홍길동",
Content = "게시판 테스트입니다.",
RegDate = DateTime.Now
},
new BoardModel
{
Id = 2,
Title = "두 번째 게시글",
Writer = "김철수",
Content = "MVC와 jQuery 공부 중입니다.",
RegDate = DateTime.Now
}
};
// 게시판 페이지
public IActionResult Index()
{
return View();
}
// 목록 조회
[HttpGet]
public IActionResult GetList()
{
return Json(boards.OrderByDescending(x => x.Id).ToList());
}
// 게시글 등록
[HttpPost]
public IActionResult Insert(BoardModel model)
{
model.Id = boards.Count == 0
? 1
: boards.Max(x => x.Id) + 1;
model.RegDate = DateTime.Now;
boards.Add(model);
return Json(new
{
success = true,
message = "등록되었습니다."
});
}
// 게시글 수정
[HttpPost]
public IActionResult Update(BoardModel model)
{
var board = boards.FirstOrDefault(x => x.Id == model.Id);
if (board == null)
{
return NotFound(new
{
success = false,
message = "게시글을 찾을 수 없습니다."
});
}
board.Title = model.Title;
board.Writer = model.Writer;
board.Content = model.Content;
return Json(new
{
success = true,
message = "수정되었습니다."
});
}
// 게시글 삭제
[HttpPost]
public IActionResult Delete(int id)
{
var board = boards.FirstOrDefault(x => x.Id == id);
if (board == null)
{
return NotFound(new
{
success = false,
message = "게시글을 찾을 수 없습니다."
});
}
boards.Remove(board);
return Json(new
{
success = true,
message = "삭제되었습니다."
});
}
}
}
여기에서 이 부분은 데이터베이스 대신 메모리에 데이터를 저장한다.
static 메서드라서 메모리에 데이터를 저장하지만 서버가 재시작되면 전에 등록했던 게시글은 사라진다.
private static List<BoardModel> boards = new();
Views/Board/Index.cshtml
게시글 목록과 등록 및 수정 입력 화면을 만든다.
@{
ViewData["Title"] = "게시판";
}
<h2 class="mb-4">게시판 관리</h2>
@Html.AntiForgeryToken()
<!-- 게시글 입력 영역-->
<div class="card p-3 mb-4">
<h5>게시글 등록 / 수정</h5>
<input type="hidden" id="Id" value="0" />
<div class="mb-3">
<label>제목</label>
<input type="text" id="Title" class="form-control" />
</div>
<div class="mb-3">
<label>작성자</label>
<input type="text" id="Writer" class="form-control" />
</div>
<div class="mb-3">
<label>내용</label>
<textarea id="Content" class="form-control" rows="5"></textarea>
</div>
<div>
<button type="button" id="btnSave" class="btn btn-primary">저장</button>
<button type="button" id="btnReset" class="btn btn-secondary">초기화</button>
</div>
</div>
<!-- 게시글 목록 영역 -->
<div class="card p-3">
<div class="d-flex justify-content-between mb-3">
<h5>게시글 목록</h5>
<button type="button" id="btnSearch" class="btn btn-outline-primary btn-sm">
새로고침
</button>
</div>
<table class="table table-bordered table-hover">
<thead class="table-light">
<tr>
<th width="70">번호</th>
<th>제목</th>
<th width="120">작성자</th>
<th width="180">작성일</th>
<th width="150">관리</th>
</tr>
</thead>
<tbody id="boardList">
</tbody>
</table>
</div>
@section Scripts{
<script src="~/js/board.js"
asp-append-version="true"></script>
}
wwwroot/js/board.js 를 생성해서 자바스크립트 파일을 불러오는 방법을 사용하겠다.
$(document).ready(function () {
// 페이지 시작 시 목록 조회
getList();
// 게시글 목록 조회
function getList() {
$.ajax({
url: '/Board/GetList',
type: "GET",
success: function (data) {
$('#boardList').empty();
if (data.length === 0) {
$("#boardList").append(
$("<tr>").append(
$("<td>", {
colspan: 5,
class: "text-center",
text: "등록된 게시글이 없습니다."
})
)
);
return;
}
$.each(data, function (index, item) {
var tr = $("<tr>");
tr.append(
$("<td>").text(item.id)
);
tr.append(
$("<td>").text(item.title)
);
tr.append(
$("<td>").text(item.writer)
);
tr.append(
$("<td>").text(
new Date(item.regDate).toLocaleString()
)
);
// 수정 버튼
var editButton = $("<button>", {
type: "button",
class: "btn btn-warning btn-sm me-1",
text: "수정"
});
editButton.on("click", function () {
editBoard(item);
});
// 삭제 버튼
var deleteButton = $("<button>", {
type: "button",
class: "btn btn-danger btn-sm",
text: "삭제"
});
deleteButton.on("click", function () {
deleteBoard(item.id);
});
tr.append(
$("<td>").append(editButton, deleteButton)
);
$("#boardList").append(tr);
});
},
error: function () {
alert("목록 조회 실패");
}
});
}
// 게시글 등록 및 수정
$("#btnSave").click(function () {
var id = $("#Id").val();
var data = {
Id: id,
Title: $("#Title").val(),
Writer: $("#Writer").val(),
Content: $("#Content").val(),
};
if (!data.Title.trim()) {
alert("제목을 입력하세요.");
return;
}
if (!data.Writer.trim()) {
alert("작성자를 입력하세요.");
return;
}
if (!data.Content.trim()) {
alert("내용을 입력하세요.");
return;
}
// Id가 0이면 등록, 아니면 수정
var url = id == 0 ? "/Board/Insert" : "/Board/Update";
$.ajax({
url: url,
type: "POST",
headers: {
"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
},
data: data,
success: function (response) {
alert(response.message);
resetForm();
getList();
},
error: function (xhr) {
alert(xhr.responseJSON.message || "저장 중 오류가 발생했습니다.");
}
});
});
// 게시글 수정
function editBoard(item) {
$("#Id").val(item.id);
$("#Title").val(item.title);
$("#Writer").val(item.writer);
$("#Content").val(item.content);
$("#btnSave").text("수정하기");
$("html, body").animate({ scrollTop: 0 }, 300);
}
// 게시글 삭제
function deleteBoard(id) {
if (!confirm("정말 삭제하시겠습니까?")) {
return;
}
$.ajax({
url: "/Board/Delete",
type: "POST",
headers: {
"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
},
data: {
id: id
},
success: function (response) {
alert(response.message);
getList();
},
error: function () {
alert("삭제 중 오류가 발생했습니다.");
}
});
}
// 입력 초기화
function resetForm() {
$("#Id").val(0);
$("#Title").val("");
$("#Writer").val("");
$("#Content").val("");
$("#btnSave").text("저장");
}
// 초기화 버튼
$("#btnReset").click(function () {
resetForm();
});
// 새로고침 버튼
$("#btnSearch").click(function () {
getList();
});
});
해당 jQuery JavaScript를 Index.cshtml의 sectionScripts 부분에서 파일로 가져온다.
앞에서 만든 BoardController.cs의 POST 메서드 3개에 다음 속성을 추가한다.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Insert(BoardModel model)
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Update(BoardModel model)
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
이렇게 하면 View에서 발급한 Anti-Forgery Token을 AJAN 요청에 함께 전달하여 CSRF 공격을 방어할 수 있다.
서버 실행후 다음 주소로 접속해 본다.
https://localhost:7175/Board/Index
테스트 내용