ASP.NET Core MVC jQuery SQL Server

개발공부하자·2026년 11월 3일

asp.ner MVC jQuery

목록 보기
3/6

SQL Server 데이터베이스 생성

SQL Server Management Studio(SSMS)를 실행후
새 쿼리를 열고 다음 SQL을 실행한다.

CREATE DATABASE MvcBoardDB;
실행

USE MvcBoardDB;
실행

CREATE TABLE Board
(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Title NVARCHAR(200) NOT NULL,
    Writer NVARCHAR(100) NOT NULL,
    Content NVARCHAR(MAX) NULL,
    RegDate DATETIME2 NOT NULL DEFAULT GETDATE()
);
실행

테스트 데이터도 넣는다.

INSERT INTO Board
(
    Title,
    Writer,
    Content
)
VALUES
(
    '첫 번째 게시글',
    '홍길동',
    'SQL Server 연동 테스트입니다.'
),
(
    '두 번째 게시글',
    '김철수',
    'Entity Framework Core 테스트입니다.'
);

이제 데이터베이스와 테이블이 준비되었다.

Entity Framework Core 설치

터미널에서 패키지 설치를 해준다

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

ConnectionStrings 설정

프로젝트에 우클릭후 사용자 암호 관리를 들어간다.

secret.json 파일에 ConnectionStrings를 설정해주자

{
  "ConnectionStrings:DefaultConnection": "Server=localhost;Database=MvcBoardDB;Trusted_Connection=True;TrustServerCertificate=True;"
}

Model 생성

Models/BoardModel.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcJqueryDemo.Models
{
    [Table("Board")]
    public class BoardModel
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "제목을 입력하세요.")]
        [MaxLength(100, ErrorMessage = "제목은 100자 이하로 입력하세요.")]
        public string Title { get; set; } = "";

        [Required(ErrorMessage = "작성자를 입력하세요.")]
        [MaxLength(50, ErrorMessage = "작성자는 50자 이하로 입력하세요.")]
        public string Writer { get; set; } = "";
        
        [Required(ErrorMessage = "내용을 입력하세요.")]
        public string Content { get; set; } = "";

        public DateTime RegDate { get; set; }
    }
}

여기서 주오 어노테이션은 다음과 같다

  • [Table("Board")] : 연결할 테이블 지정
  • [Key] : 기본키 지정
  • [Required] : 필수값 지정
  • [MaxLength(100)] : 최대 길이 지정

DbContext 생성

Data/ApplicationDbContext.cs

using Microsoft.EntityFrameworkCore;

namespace MvcJqueryDemo.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }
        public DbSet<Models.BoardModel> Boards { get; set; }
    
    }
}

이 코드가 EF Core의 핵심이다.

public DbSet<Models.BoardModel> Boards { get; set; }

이제 C#에서 Boards를 통해 SQL Server의 Board 테이블에 접근할 수 있다.

Program.cs 설정

Program.cs 에서 DbContext를 등록한다.

using Microsoft.EntityFrameworkCore;
using MvcJqueryDemo.Data;

var builder = WebApplication.CreateBuilder(args);

// MVC 등록
builder.Services.AddControllersWithViews();

// DB 연결 등록
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")
    )
);

var app = builder.Build();

이 설정을 통해 ASP.NET Core가 DbContext 객체를 자동으로 생성하고 필요한 곳에 전달해 준다. 이 기능을 DI(Dependency Injection)이라고 한다.

Service 계층 만들기

이제 실무적은 구조를 만들어 보겠다.
Controller에서 직접 DB를 조회할 수도 있지만, 업무 로직과 DB 처리 로직을 분리하면 유지보수가 쉬워진다.

IBoardService.cs

Services/IBoardService.cs

using MvcJqueryDemo.Models;

namespace MvcJqueryDemo.Services
{
    public interface IBoardService
    {
        Task<List<BoardModel>> GetListAsync();

        Task<int> InsertAsync(BoardModel model);

        Task<bool> UpdateAsync(BoardModel model);

        Task<bool> DeleteAsync(int id);
    }
}

인터페이스는 서비스가 제공할 기능만 정의한다.

BoardService.cs

Services/BoardService.cs

using Microsoft.EntityFrameworkCore;
using MvcJqueryDemo.Data;
using MvcJqueryDemo.Models;

namespace MvcJqueryDemo.Services
{
    public class BoardService : IBoardService
    {
        private readonly ApplicationDbContext _context;

        public BoardService(ApplicationDbContext context)
        {
            _context = context;
        }

        // 목록 조회
        public async Task<List<BoardModel>> GetListAsync()
        {
            return await _context.Boards
                .AsNoTracking()
                .OrderByDescending(x => x.Id)
                .ToListAsync();
        }

        // 게시글 등록
        public async Task<int> InsertAsync(BoardModel model)
        {
            model.RegDate = DateTime.Now;

            _context.Boards.Add(model);

            await _context.SaveChangesAsync();

            return model.Id;
        }
        public async Task<bool> UpdateAsync(BoardModel model)
        {
            var board = await _context.Boards.FirstOrDefaultAsync(x => x.Id == model.Id);

            if(board == null)
            {
                return false;
            }

            board.Title = model.Title;
            board.Writer = model.Writer;
            board.Content = model.Content;

            await _context.SaveChangesAsync();

            return true;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var board = await _context.Boards.FirstOrDefaultAsync(x => x.Id == id);

            if(board == null)
            {
                return false;
            }

            _context.Boards.Remove(board);

            await _context.SaveChangesAsync();

            return true;
        }
    }
}

여기서 기억해야할 EF Core 메서드가 있다.

  • ToListAsync() : 목록 조회
  • FirstOrDefaultAsync() : 단일 데이터 조회
  • Add() : 데이터 추가
  • Remove() : 데이터 삭제
  • SaveChangesAsync() : DB에 변경사항 저장
  • AsNoTracking() : 조회 전용 데이터 추적 생략

    SaveChangesAsync()를 반드시 호출해야 실제 DB에 변경사항이 반영된다.

DI에 Service 등록

Program.cs에 다음 코드를 추가한다

// DB 연결 등록
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

// 보드 서비스 등록(인터페이스를 불러오면 구현체가 실행됨)
builder.Services.AddScoped<IBoardService, BoardService>();

AddScoped는 HTTP 요청마다 서비스 인스턴스를 생성하고 해당 요청 범위에서 사용하도록 한다.

BoardController 수정

이제 기존 BoardController.cs를 수정한다.
기존 List 방식은 제거하고 Service를 통해 DB에 접근하도록 변경한다.

using Microsoft.AspNetCore.Mvc;
using MvcJqueryDemo.Models;
using MvcJqueryDemo.Services;

namespace MvcJqueryDemo.Controllers
{
    public class BoardController : Controller
    {
        private readonly IBoardService _boardService;

        public BoardController(IBoardService boardService)
        {
            _boardService = boardService;
        }

        // 게시판 페이지
        public IActionResult Index()
        {
            return View();
        }

        // 목록 조회
        [HttpGet]
        public async Task<IActionResult> GetList()
        {
            var result = await _boardService.GetListAsync();
            return Json(result);
        }

        // 게시글 등록
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Insert(BoardModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new
                {
                    message = "입력값을 확인하세요."
                });
            }

            var id = await _boardService.InsertAsync(model);

            return Json(new
            {
                success = true,
                message = "등록되었습니다.",
                id = id
            });
        }

        // 게시글 수정
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Update(BoardModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new
                {
                    message = "입력값을 확인하세요."
                });
            }

            var result = await _boardService.UpdateAsync(model);

            if (!result)
            {
                return NotFound(new
                {
                    message = "게시글을 찾을 수 없습니다."
                });
            }

            return Json(new
            {
                success = true,
                message = "수정되었습니다."
            });
        }

        // 게시글 삭제
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            var result = await _boardService.DeleteAsync(id);

            if (!result)
            {
                return NotFound(new
                {
                    message = "게시글을 찾을 수 없습니다."
                });
            }

            return Json(new
            {
                success = true,
                message = "삭제되었습니다."
            });
        }
    }
}

이제 Controller는 DB를 직접 다루지 않는다.

View와 jQuery 연결

앞에서만든 보드의 Index.cshtml과 자바스크립트 파일을 그대로 사용할 수 있다.
현재 View에는 Anti-Forgery Token이 있다.

@Html.AntiForgeryToken()

그리고 AJAX POST 요청에는 다음 헤더를 전달한다.

headers: {
    "RequestVerificationToken":
        $('input[name="__RequestVerificationToken"]').val()
}

Anti-Forgery 설정 추가

ASP.NET Core가 해당 헤더를 인식하도록 Program.cs에 설정을 추가한다.

// DB 연결 등록
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

// 보드 서비스 등록(인터페이스를 불러오면 구현체가 실행됨)
builder.Services.AddScoped<IBoardService, BoardService>();

// POST 요청 시 CSRF 공격 방지를 위한 토큰 검증
builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "RequestVerificationToken";
});

이제 POST 요청의 CSRF 검증이 정상적으로 동작한다.

profile
개발공부하자

0개의 댓글