본문 바로가기
ASP.NET Core

ASP.NET Core MVC] ViewData, [ViewData] attribute, ViewBag

by Fastlane 2022. 1. 10.
728x90
반응형

View로 데이터를 전달하는 몇가지 방법이 있다. 

  • Strongly typed data: 데이터 type을 명확하게 지정할 수 있음
    • viewmodel
  • Weakly typed data: 데이터 type을 명확하게 정하지 않음, 적은 양의 데이터를 전달하기 위해 사용
    • ViewData (ViewDataAttribute)
    • ViewBag

 

ViewData

string keys를 통해 접근하는 ViewDataDictionary object이다. 

string을 제외하고, 특정 형식을 cast해야 view에서 사용할 수 있다. 

public IActionResult SomeAction()
{
    ViewData["Greeting"] = "Hello";
    ViewData["Address"]  = new Address()
    {
        Name = "Steve",
        Street = "123 Main St",
        City = "Hudson",
        State = "OH",
        PostalCode = "44236"
    };

    return View();
}
@{
    // Since Address isn't a string, it requires a cast.
    var address = ViewData["Address"] as Address;
}

@ViewData["Greeting"] World!

<address>
    @address.Name<br>
    @address.Street<br>
    @address.City, @address.State @address.PostalCode
</address>

 

[ViewData] Attriute

public class HomeController : Controller
{
    [ViewData]
    public string Title { get; set; }

    public IActionResult About()
    {
        Title = "About Us";
        ViewData["Message"] = "Your application description page.";

        return View();
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>@ViewData["Title"] - WebApplication</title>
    ...

 

ViewBag

캐스팅이 필요하지 않다. 

@ViewBag.Greeting World!

<address>
    @ViewBag.Address.Name<br>
    @ViewBag.Address.Street<br>
    @ViewBag.Address.City, @ViewBag.Address.State @ViewBag.Address.PostalCode
</address>

간단하게 Null값을 확인한다. @ViewBag.Person?.Name

 

728x90
반응형

댓글