ASP. net mvc Tip #19-use the nvelocity view template engine

Source: Internet
Author: User

ASP. net mvc Tip #19-use the nvelocity view template engine
ASP. net mvc Tip #19-use the nvelocity view Engine

Original American: http://weblogs.asp.net/stephenwalther/archive/2008/07/14/asp-net-mvc-tip-19-use-the-nvelocity-view-engine.aspx
Http://www.cnblogs.com/mike108mvp

Note: The translation level is limited. If there are any mistakes or mistakes in the translation, you are welcome to criticize and correct them. Thank you.

Note: ASP. net mvc qq chat group 1215279 welcome to friends interested in ASP. NET MVC

In this post, I demonstrated how to use the nvelocity view template engine instead of the common web forms view engine when you present a view in ASP. NET MVC application.

By default, you can create an ASP. NET web form file (. aspx) to create a view for ASP. net mvc application. You do not have. If you like, you can replace the web forms view engine and use other view template engines. In this post, I will demonstrate how to use the nvelocity view template engine.

Why use the nvelocity template engine instead of the common Web Forms Template engine? You may have several different reasons. First, nvelocity is introduced from the velocity project of Java Apache Software Foundation to the. NET Framework version. If you are converting a current Java applicationProgramMigrate to the. NET platform, and the program uses the velocity template engine, so using the nvelocity template engine can make the migration process smoother.

Second, you may prefer the nvelocity template engine syntax compared with the syntax of ASP. NET web forms. The velocity template engine language is designed specifically to Create HTML pages. Velocity provides you with a very clean syntax for general operations, such as looping a batch of database records, and display each record in an HTML page (which can be considered as a specialized language in the HTML field ).

Configure nvelocity for ASP. NET MVC

It took me a long time to figure out how to configure nvelocity to work with ASP. net mvc. The problem is that you have to extract files from two different projects and let them work together (some assembly is hidden in nested folders ).

Here is the step for nvelocity to work:

Step 1:
Download and unzip the mvccontrib binary file from the following website: http://www.CodePlex.com/MvcContrib

Step 2:
Download and unzip the castle project from the following website: http://www.castleproject.org/castle/download.html

Step 3:
After extracting step 2, navigate to the bindirectory to decompress the external-dependencies.zip file. This file contains the nvelocity. dll assembly.

Step 4:
Create a New Visual Studio 2008 ASP. net mvc application.

Step 5:
Add an mvccontrib. Castle reference. You can find it from the file downloaded in step 1. (Mvccontrib. Castle assembly is part of the mvccontrib project, not part of the castle Project)

Step 6
Add a reference to the nvelocity assembly that you extract in step 3.

There are two important warnings. First, do not use the nvelocity assembly in http://nvelocity.sourceforge.net. If you search for nvelocity in a search engine, this is the first search result. Unfortunately, this project has not been updated since 2003, and the nvelocity here is very outdated. You should use the nvelocity assembly in the castle project.

Second, make sure that you have not blocked any files before extracting them. You can right-click a file and choose Properties> unblock to unblock a file. If you fail to unblock a compressed file, you may encounter security issues when you try to use these files in Visual Studio 2008.

Use the nvelocity template engine

After completing these steps, you can start using the nvelocity template engine. There are two ways to instruct ASP. Net MVC framework that you want to use the nvelocity template engine instead of the common Web Forms Template engine.

First, you can modify the viewengine attribute in the Controller action before returning a view. For exampleCodeThe homecontroller in the list uses nvelocity for index () action.

Listing 1-homecontroller. CS (C #)

Using System. Web. MVC;
Using Tip19.models;

Namespace Tip19.controllers
{
Public   Class Homecontroller: Controller
{
Private Moviedatacontext _ datacontext =   New Moviedatacontext ();

Public Actionresult index ()
{
This. Viewengine= NewMvccontrib. Castle. nvelocityviewfactory ();

ReturnView (_ datacontext. Movies );
}
}
}

If you only want to use nvelocity on some pages of your web application, setting the viewengine attribute is an easy way to replace the view template engine. However, if you want all your views to use nvelocity, you should consider creating a custom controller factory. In code list 2, the custom controller factory changes the default template engine to nvelocity.

Listing 2-velocitycontrollerfactory. CS (C #)

Using System;
Using System. Web. MVC;

Namespace Tip19.controllers
{
Public   Class Velocitycontrollerfactory: defaultcontrollerfactory
{
Protected   Override Icontroller getcontrollerinstance (type controllertype)
{
Icontroller =   Base . Getcontrollerinstance (controllertype );
Controller velocitycontroller = Controller As Controller;
If (Velocitycontroller ! =   Null )
{< br> var context = New controllercontext ( This . requestcontext, velocitycontroller);
velocitycontroller. viewengine = New mvccontrib. castle. nvelocityviewfactory ();
}  
Return Controller;
}  
}  
}

To use a custom controller factory, you must register this factory in the global. asax file of your application. The modified global. asax in code listing 3 contains a call to the setcontrollerfactory () method in the application_start () method.

Listing 3-Global. asax. CS (C #)

Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Web. MVC;
Using System. Web. Routing;
Using Tip19.controllers;

Namespace Tip19
{
Public   Class Globalapplication: system. Web. httpapplication
{
Public   Static   Void Registerroutes (routecollection routes)
{
Routes. ignoreroute ( " {Resource}. axd/{* pathinfo} " );

Routes. maproute (
" Default " , // Route name
" {Controller}/{action}/{ID} " , // URL with Parameters
New   {Controller= "Home", Action= "Index", ID= ""} // Parameter defaults
);

}

Protected   Void Application_start ()
{
Controllerbuilder. Current. setcontrollerfactory (Typeof(Velocitycontrollerfactory ));
Registerroutes (routetable. routes );
}
}
}

After you register velocitycontrollerfactory, All controllers in your MVC application use the nvelocity template engine by default. You no longer need to modify the viewengine attribute in each controller action.

Create an nvelocity View

You can create an nvelocity view by creating a file with the suffix. VM. Visual Studio does not have a template that contains velocity views. You can create an HTML pageand change the extension name of a volume from .htm to. VM to create a velocity view.

For example, view in code listing 4 contains a velocity template, which displays all movies passed in homecontroller in code listing 1 on the page.

Listing 4-views \ home \ index. VM

<! Doctype HTML public " -// W3C // dtd xhtml 1.0 transitional // en "   " Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd " >
< HTML xmlns = " Http://www.w3.org/1999/xhtml "   >
< Head >
< Title > Untitled page </ Title >
</ Head >
< Body >


# Foreach ($ Movie In $ Viewdata. Model)
< Li > < A href = " /Home/edit/$ movie. ID " > $ Movie. Title </ A > </ Li >
# End

</ Body >
</ Html >

View in code list 4 uses the velocity template language to display movies. Pay attention to the... The each code block is created using the velocity command # foreach and # End. Note that you use $ to identify variables. Therefore, you can use the expression $ viewdata. Model to refer to viewdata. model. Velocity is case insensitive.

The Apache Software Foundation website has a complete reference document for the velocity language. This website also provides a quick start guide. Please refer:

Http://velocity.apache.org/engine/releases/velocity-1.5/vtl-reference-guide.html

Http://velocity.apache.org/engine/releases/velocity-1.5/user-guide.html

Summary

In this post, I demonstrated how to use the nvelocity template engine in ASP. NET MVC application. I demonstrate two methods to replace the default web forms view engine. You can specify a specific view engine for a specific controller action and specify a specific view engine for all controller actions.

I certainly do not recommend that you use nvelocity instead of the web forms view engine. My real purpose in this post is to demonstrate the flexibility of ASP. net mvc. If you do not like any part of ASP. net mvc framework, you can replace it.

Download: http://weblogs.asp.net/blogs/stephenwalther/Downloads/Tip19/Tip19.zip

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.