T4 in ASP. NET MVC

Source: Internet
Author: User
Tags visual studio 2010

Each time you use the Add View or add Controller feature, you use the T4 template in an ASP. NET MVC project. These templates are located in the Visual Studio installation of the Common7\ide\itemtemplates\csharp\web\mvc 2\codetemplates folder. The Visual Basic version of the template is also available, but I'll use it as an exercise for the reader to infer the folder name.

The templates themselves are sufficient to illustrate the value and functionality of T4. For example, here is an excerpt from list.tt in the AddView subfolder of Codetemplates:

if (! String.IsNullOrEmpty (mvcviewdatatypegenericstring)) {  dictionary<string, string> properties =     New Dictionary<string, string> ();  Filterproperties (Mvchost.viewdatatype, properties);#>  <table>    <tr>      <th></th >http://util.cnblogs.com/insertcode.aspx<#  foreach (keyvaluepair<string, string> property in Properties) {#>      <th>        <#= property. Key #>      </th><#  }#>

  

List.tt's job is to generate an. aspx file that will display a collection of model objects in tabular form. In the template, you can see the table, TR, and th tags that you wrote. To build an. aspx file, the template requires some contextual information, such as the name of the master page that should be used and the type of the model. The template can retrieve this information from its host object. The host object resides between the template and the T4 engine, and enables the template to access resources such as local files and environment settings. Typically, the host is Visual Studio, but the MVC team creates a custom host of type Mvctexttemplatehost in the Microsoft.VisualStudio.Web.Extensions assembly. This is a custom host object that inherits the information you enter in the Add View and Add Controllers dialog boxes, which are the closest thing you'll find to the wizard in an MVC project.

LIST.TT will traverse the visible properties of the strongly typed model object and create a table with each attribute column. The template uses reflection to find the available properties of the model in the Filterproperties method. Filterproperties is a helper method that is later defined in the template file. The template also sets a link to navigate to edit and detail operations, and sets the appropriate @ Page or @ Control directives for. aspx based on whether you are creating a view or a partial view.

When the template finishes running, you will see a brand new. aspx view that contains everything you need to display a collection of model objects. You may open the. aspx file and fine-tune it so that the view is visually consistent with the view in the rest of the application.

If you find that the same changes are always made to these generated views (or CONTROLLER.TT generated controller code), you can save time by modifying the template itself. For example, you can modify a built-in template to add class properties to the style rules and even more important content used in the project. Keep in mind that modifying the template files in the Visual Studio installation directory will change the code that is generated in all projects that are made on your computer. You can also do this if you want to change the code that is generated for a single project.

Individual Items T4 Custom

If you want to generate a custom version of the template based on the code for each project, first copy the Codetemplates folder in the Visual Studio installation, and then paste it into the root of your ASP. NET. NET MVC project. However, you do not have to copy all of the templates into your project. You can copy only the templates that you want to modify. There are 6 MVC code generation templates, 1 for adding a controller (CONTROLLER.TT), and 5 for adding views (Create.tt, Details.tt, Edit.tt, Empty.tt, list.tt). If a template exists in your project, the template overrides the template in the Visual Studio installation directory.

When you add a. tt file to a Visual Studio solution, the IDE automatically assigns the. tt file to the custom tool settings for TextTemplatingFileGenerator. If you created the simple.tt template that I described earlier, you already see this situation. However, this is not an appropriate setting for the MVC T4 template. The MVC tools for Visual Studio will invoke these templates at the appropriate time and create special Mvctexttemplatehost objects during template processing. Therefore, after you copy the template to your project, the second step is to open the Properties window for each template file, and then remove the custom tools setting (Leave this setting blank). At this point, you can customize your template.

--------------------------------------------------------------------------------------------------------------- ------------

Mvctexttemplatehost property Note that not all properties on the Mvctexttemplatehost object apply to each context. These templates will be executed when you invoke the Add view and Add controller context menu items. Both of these operations can use the Namespace property and set it to the appropriate value. However, the MasterPage property is only set to a valid value during the Add view operation and contains the value that the user entered for the MasterPage name in the Add View dialog box. --------------------------------------------------------------------------------------------------------------- ------------For example, suppose you do not want the controller to perform an index operation. Instead, you prefer to use the default action List. You can open the Controller.tt template in the Codetemplates\addcontroller folder and change the corresponding area of the code to the following:
public class <#= Mvchost.controllername #>: controller{  //GET:/<#= mvchost.controllerrootname #>/ Public  ActionResult List ()  {    return View ();  } ...

  

This is a simple change, but it can save you and your team a considerable amount of time throughout the large project life cycle.

Further-T4MVC

In the summer of 2009, David Ebbo of the ASP. T4MVC, a T4 template, is designed to generate a strongly typed helper in an ASP. NET MVC application. Over time, Ebbo has perfected the template, and you can now download the template from Aspnet.codeplex.com/wikipage?title=t4mvc.

The T4mvc template is a traditional T4 template. Add t4mvc.tt and its associated settings file (T4MVC.SETTINGS.T4) to your project, which will generate C # code using the TextTemplatingFileGenerator custom tool. T4MVC will help you eliminate many of the fantastic string literals in your MVC application. For example, a template will perform a task of scanning the Content and Scripts folders in a project and generating classes with static properties to represent individual scripts and content fragments.

The generated code means that you can render a partial view of the Logonusercontrol provided by the default MVC project with that code:

<% html.renderpartial (MVC. Shared.Views.LogOnUserControl); %>
Previously, you might have used string literals:
<% html.renderpartial ("Logonusercontrol"); %>

If someone renames, moves, or deletes Logonusercontrol, the strongly typed code generates a compilation error when the view is compiled. In addition to strongly typed access to view and partial views, the T4MVC template provides strongly typed access to all files in the Content and Scripts folders, as well as controller and controller operations.

You can create action links, return view results, and even use T4MVC-generated classes when building routing tables for your application. Note that when you first add T4MVC to your project, you will see some warnings generated in the Error List window of the IDE. These warnings are just t4mvc to introduce you to some of the changes that are applied to your code. Most of these changes do not alter the behavior of the application; The T4mvc template only adds some local keywords to the Controller class definition and makes the non-virtual operation method a virtual method. For more information about T4MVC, check out Ebbo's blog at Blogs.msdn.com/davidebb.

T4 is a fantastic asset in Visual Studio, but it's not a well-known template. This article provides you with everything you need to get started with your custom templates in an ASP. NET MVC project. Hopefully, you'll also find other uses for the T4 template outside of the WEB application project. You should also try out T4MVC templates in your project, because they make your code easier to maintain and refactor. Looking to the future, T4 technology in Visual Studio 2010 will add dedicated project templates and precompiled templates to make it more perfect.

Reprint: Https://msdn.microsoft.com/zh-sg/magazine/ee291528.aspx









T4 in ASP. NET MVC

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.