$ViewData.User.Name<br />
</body>
</html>
当然,我们也可以将其注册成默认视图引擎,免得每次要创建 IView 传递给 View()。
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new NVelocityViewEngine());
RegisterRoutes(RouteTable.Routes);
}
}
或者写一个 IResultFilter,标注在需要使用 NVelocityViewEngine 的 ActionMethod 上。
public class NVelocityViewAttribute : ActionFilterAttribute
{
public NVelocityViewAttribute()
{
}
public NVelocityViewAttribute(string viewPath)
{
this.ViewPath = viewPath;
}
public string ViewPath { get; set; }
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
if (String.IsNullOrEmpty(ViewPath))
{
foreach (var ext in new[] { "html", "htm" })
{
ViewPath = String.Format("~/Views/{0}/{1}.{2}",
filterContext.RouteData.GetRequiredString("controller"),
filterContext.RouteData.GetRequiredString("action"),
ext);
if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(ViewPath))) break;
}
}
var result = filterContext.Result as ViewResult;
if (result != null)
{
result.View = new NVelocityView(filterContext, ViewPath);
}
}
}
现在使用起来更加方便了。
[NVelocityView]
public ActionResult Index()
{
ViewData["user"] = new
{
Name = "Tom",
Age = 13
};
return View();
}
还可以手工指定一个模板。
[NVelocityView("/Views/Test/Index2.htm")]
public ActionResult Index()
{
ViewData["user"] = new
{
Name = "Tom",
Age = 13
};
return View();
}
文章源自:烈火网,原文:http://zhan.liehuo.net/a/200908/207790.html