Introduction
Here, we are going to customize T4 template. Customization of T4 template is very important for developing a large application. First of all, let's learn what is T4 template and why we need it in ASP.NET MVC in short.
According to MSDN, T4 is a general-purpose templating engine you can use to generate C# code, Visual Basic code, XML, HTML, or text of any kind. In ASP.NET MVC, we generate the view using our data model class. Actually, we generate this view based on this T4 template. Just think if you have more than 200 add forms in your application and definitely this add form has a unique design for your application. Then what will you do? Just manually add those forms in your application or you want your customized form that MVC will generate for you for every single class model? Let's make a customized form.
Using the Code
At first, we need to bring the T4 template folder in our application. Because we don't want to change the default template, we will change the new template. We can find the templates in the following location :[Visual Studio Install Directory]\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates\.
Please note that when you copy the above folder (really, any time you add a .tt file) into the project, you will see warnings as follows:
Then hit ok and remove all the .cs and .chtml files. Add Controller and Add View folders like:
That's all. Now it is time for customizing according to our model property.
Model
public class Sample
{
public Int32 ID { get; set; }
public String Name { get; set; }
public String Designation { get; set; }
public DateTime JoiningDate { get; set; }
public Decimal Salary { get; set; }
}
Our desired form will look like:
Here Input type will generate according to model property. Name and Designation will be text type, Joining Date will be a jquery datepicker and the Salary textbox will be numeric textbox that will allow only numeric value.
Create.tt
if (property.UnderlyingType == typeof(DateTime)) { #>
@Html.TextBoxFor(model => model.<#= property.Name #>,
new { @class="datepicker"}) <#
}
else if (property.UnderlyingType == typeof(double) ||
property.UnderlyingType == typeof(decimal)|| property.UnderlyingType == typeof(float)) {
@Html.TextBoxFor(model => model.<#= property.Name #>,
new { @class="onlyNumeric", @placeholder="Please Enter Your
"+@Html.DisplayNameFor(model => model.<#= property.Name #>)+" (Only Numeric)" })
}
else{
#>
@Html.TextBoxFor(model => model.<#= property.Name #>,
new {@placeholder="Please Enter Your "+@Html.DisplayNameFor(model =>
model.<#= property.Name #>)})
Create.cstml
I have added this project. Please go through it. Hopefully then, you will understand clearly.
History
- 26th February, 2015: Initial version