Dynamic v. Strongly Typed Views
There are three ways to pass information from a controller to a view in ASP.NET MVC 3:
- As a strongly typed model object.
- As a dynamic type (using @model dynamic)
- Using the ViewBag
I’ve written a simple MVC 3 Top Blog application to compare and contrast dynamic and strongly typed views. The controller starts out with a simple list of blogs:
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.Web.Mvc;
3:
4: namespace Mvc3ViewDemo.Controllers {
5:
6: public class Blog {
7: public string Name;
8: public string URL;
9: }
10:
11: public class HomeController : Controller {
12:
13: List<Blog> topBlogs = new List<Blog>
14: {
15: new Blog { Name = "ScottGu", URL = "http://weblogs.asp.net/scottgu/"},
16: new Blog { Name = "Scott Hanselman", URL = "http://www.hanselman.com/blog/"},
17: new Blog { Name = "Jon Galloway", URL = "http://www.asp.net/mvc"}
18: };
19:
20: public ActionResult IndexNotStonglyTyped() {
21: return View(topBlogs);
22: }
23:
24: public ActionResult About() {
25: ViewBag.Message = "Welcome to ASP.NET MVC!";
26: return View();
27: }
28: }
29: }
Right click in the IndexNotStonglyTyped() method and add a Razor view.
Make sure the Create a strongly-typed view box is not checked. The resulting view doesn’t contain much:
[!code-cshtmlMain]
1: @{
2: ViewBag.Title = "IndexNotStonglyTyped";
3: }
4:
5: <h2>IndexNotStonglyTyped</h2>
6:
7: On the first line of the Views\Home\IndexNotStonglyTyped.cshtml file, add the model directive and the dynamic keyword.
[!code-cshtmlMain]
1: @model dynamic
Because we’re using a dynamic and not a strongly typed view, intellisense doesn’t help us. The completed code is shown below:
[!code-cshtmlMain]
1: @model dynamic
2:
3: @{
4: ViewBag.Title = "IndexNotStonglyTyped";
5: }
6:
7: <h2>Index Not Stongly Typed</h2>
8:
9: <p>
10: <ul>
11: @foreach (var blog in Model) {
12: <li>
13: <a href="@blog.URL">@blog.Name</a>
14: </li>
15: }
16: </ul>
17: </p>
Now we’ll add a strongly typed view. Add the following code to the controller:
[!code-csharpMain]
1: public ActionResult StonglyTypedIndex() {
2: return View(topBlogs);
3: }
Notice it’s exactly the same return View(topBlogs); call as the non-strongly typed view. Right click inside of StonglyTypedIndex() and select Add View. This time select the Blog Model class and select List as the Scaffold template.
Inside the new view template we get intellisense support.
The c# project can be downloaded here.
|