Hello MVC

Jaemyeong Lee·2025년 3월 11일

1. 프로젝트 구성 및 버전 차이

  • 강의 기준: .NET Core 3.1
  • 실습 기준: Visual Studio 2022, .NET 8.0
  • 차이점:
    • 강의에서는 Program.csStartup.cs가 분리되어 있음
    • 최신 버전에서는 이 둘이 통합되어 있음
    • 구조만 다를 뿐 기능적 차이는 거의 없음

2. MVC 아키텍처 기본 개념

MVC란?

  • Model: 데이터와 로직 담당 (예: DB에서 불러온 데이터)
  • View: 사용자 UI 구성 (HTML 기반)
  • Controller: 사용자 요청 처리 및 응답 전달
M : Model        -> 데이터 (원자재)
V : View         -> UI (인테리어)
C : Controller   -> 제어 (사용자 액션 처리)

3. MVC 구성 실습 (HelloEmpty 프로젝트)

📁 폴더 구조 만들기

HelloEmpty 프로젝트에 다음 3개의 폴더 생성:

  • Models
  • Views > Home
  • Controllers

4. Model 작성

📄 HelloMessage.cs

namespace HelloEmpty.Models
{
    public class HelloMessage
    {
        public string Message { get; set; }
    }
}

역할: 사용자에게 보여줄 텍스트 메시지를 담는 단순 모델 클래스


5. Controller 작성

📄 HomeController.cs

using HelloEmpty.Models;
using Microsoft.AspNetCore.Mvc;

namespace HelloEmpty.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            HelloMessage msg = new HelloMessage()
            {
                Message = "Welcome to ASP.NET Core!"
            };

            ViewBag.Noti = "Input message and click submit";
            return View(msg);
        }

        // POST 요청 처리
        [HttpPost]
        public IActionResult Index(HelloMessage obj)
        {
            ViewBag.Noti = "Message Changed";
            return View(obj);
        }
    }
}

설명:

  • GET 요청: 기본 메시지를 뷰에 전달
  • POST 요청: 사용자가 폼에 입력한 메시지를 다시 전달

6. View 작성

📄 Views/Home/Index.cshtml

@model HelloEmpty.Models.HelloMessage

<html>
<head>
    <title>Hello MVC!</title>
</head>
<body>
    <h1>@Model.Message</h1>
    <hr />
    <h2>@ViewBag.Noti</h2>

    <form asp-controller="Home" asp-action="Index" method="post">
        <label asp-for="Message">Enter Message</label>
        <br />
        <input type="text" asp-for="Message" />
        <br />
        <button type="submit">Submit</button>
    </form>
</body>
</html>

핵심 문법:

  • @model: 모델 바인딩 선언
  • @Model.Message, @ViewBag.Noti: C# 코드 출력
  • asp-for, asp-controller, asp-action: Razor 문법 (ASP.NET 전용)

📄 Views/_ViewImports.cshtml

@using HelloEmpty
@using HelloEmpty.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

설명: Razor에서 asp-for, asp-controller 등을 인식하기 위한 태그 헬퍼 임포트 설정


7. Program.cs 환경설정

📄 Program.cs (.NET 8 기준)

var builder = WebApplication.CreateBuilder(args);

// MVC 서비스 등록
builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthorization();

// 기본 라우팅 설정
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

8. 결과 확인

🧪 실행 결과

  • "Welcome to ASP.NET Core!"가 출력됨
  • 메시지 입력 후 Submit 클릭 시 메시지가 변경되고 아래 메시지가 변경됨:
    Message Changed

9. MVC의 장점과 단점

✅ 장점

  • 역할 분리가 명확하여 코드 관리가 쉬움
  • 재사용성, 유지보수성 향상

⚠️ 단점

  • 폴더 및 파일 구조가 많아 초보자에게는 복잡함
  • 디버깅 시 Model, View, Controller를 모두 열어봐야 할 수 있음
  • 대규모 프로젝트일수록 구성 복잡도 증가

profile
李家네_공부방

0개의 댓글