다음을 통해 공유


Dynamic v. 강력한 형식의 보기

작성자 : Rick Anderson

ASP.NET MVC 3에서 컨트롤러에서 보기로 정보를 전달하는 세 가지 방법이 있습니다.

  1. 강력한 형식의 모델 개체입니다.
  2. 동적 형식으로(동적 사용 @model )
  3. ViewBag 사용

동적 및 강력한 형식의 뷰를 비교하고 대조하기 위해 간단한 MVC 3 상위 블로그 애플리케이션을 작성했습니다. 컨트롤러는 블로그의 간단한 목록으로 시작합니다.

using System.Collections.Generic;
using System.Web.Mvc;

namespace Mvc3ViewDemo.Controllers {

    public class Blog {
        public string Name;
        public string URL;
    }

    public class HomeController : Controller {

        List<Blog> topBlogs = new List<Blog>
      { 
          new Blog { Name = "ScottGu", URL = "http://weblogs.asp.net/scottgu/"},
          new Blog { Name = "Scott Hanselman", URL = "http://www.hanselman.com/blog/"},
          new Blog { Name = "Jon Galloway", URL = "http://www.asp.net/mvc"}
      };

        public ActionResult IndexNotStonglyTyped() {
            return View(topBlogs);
        }

        public ActionResult About() {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
    }
}

IndexNotStonglyTyped() 메서드를 마우스 오른쪽 단추로 클릭하고 Razor 보기를 추가합니다.

8475.NotStronglyTypedView[1]

강력한 형식의 보기 만들기 상자가 선택되어 있지 않은지 확인합니다. 결과 보기에는 다음이 많이 포함되지 않습니다.

@{
    ViewBag.Title = "IndexNotStonglyTyped";
}

<h2>IndexNotStonglyTyped</h2>

On the first line of the Views\Home\IndexNotStonglyTyped.cshtml file, add the model directive and the dynamic keyword.
@model dynamic

강력한 형식의 뷰가 아닌 동적 뷰를 사용하고 있으므로 intellisense는 도움이 되지 않습니다. 완성된 코드는 다음과 같습니다.

@model dynamic
           
@{
    ViewBag.Title = "IndexNotStonglyTyped";
}

<h2>Index Not Stongly Typed</h2>

<p>
 <ul>
@foreach (var blog in Model) {
   <li>
    <a href="@blog.URL">@blog.Name</a>
   </li>   
}
 </ul>
</p>

6646.NotStronglyTypedView_5F00_IE[1]

이제 강력한 형식의 보기를 추가합니다. 컨트롤러에 다음 코드를 추가합니다.

public ActionResult StonglyTypedIndex() {
    return View(topBlogs);
}

정확히 동일한 반환 View(topBlogs); 를 강력한 형식이 아닌 보기로 호출합니다. StonglyTypedIndex() 내부를 마우스 오른쪽 단추로 클릭하고 보기 추가를 선택합니다. 이번에는 블로그 모델 클래스를 선택하고 스캐폴드 템플릿으로 목록을 선택합니다.

5658.StrongView[1]

새 뷰 템플릿 내에서 intellisense 지원을 받습니다.

7002.IntelliSense[1]