Let’s now look at a new feature we added with the ASP.NET MVC 3 Beta – the @model directive. The @model directive provides a cleaner and more concise way to reference strongly-typed models from view files.
To see this in action, let’s look at a (super) simple scenario where we want to implement a /Products URL that lists product categories from a database:
Below is a simple ProductsController implementation that implements the /Products URL. It retrieves a list of product categories from a database, and then passes them off to a view file to render an appropriate HTML response back to the browser:
Referencing the Model with the first ASP.NET MVC 3 Preview
If we had used Razor with the first ASP.NET MVC 3 Preview, our Index.cshtml view file would have had an @inherits statement at the top of the file that indicated that we wanted to derive the view from the “System.Web.Mvc.WebViewPage
This works (and is still supported with ASP.NET MVC 3) – but is a little verbose.
Referencing the Model using the ASP.NET MVC 3 Beta and new @model syntax
We’ve added a new @model directive with the ASP.NET MVC 3 Beta that provides a cleaner and more concise way to indicate you want to use strongly-typed model classes within your view files. You can now just write @model StrongModelType at the top of your Razor view file, and you do not need to have an @inherits or specify a view base class anymore:
The above syntax is conceptually the same as before (except with a lot fewer characters). It is easier to read and type.
Below is what a complete Index.cshtml view implementation might look like to render our original screen-shot above:
One question you might ask is – so what does my view file derive from then if it isn’t specified? By default, Razor will derive the view from the System.Web.Mvc.WebViewPage
Note: Visual Studio Code/Markup Intellisense and Colorization within Razor files aren’t enabled yet with the Beta earlier this month. You’ll see this show up in a few weeks though – and it will support full code intellisense for HTML, JavaScript, CSS and C#/VB code within Razor files.
One of the themes we’ve focused on with the ASP.NET MVC 3 and Razor releases has been to make the code you write cleaner and more concise. The above @model keyword is a small feature, but contributes nicely towards making view files even easier to read and write. I’ll be covering other nice improvements like this that are new to the ASP.NET MVC 3 Beta in future posts.
摘自:http://weblogs.asp.net/scottgu/archive/2010/10/19/asp-net-mvc-3-new-model-directive-support-in-razor.aspx