我想在 ASP.Net MVC 的服务器端生成一些 JavaScript。是否有支持此功能的 View 引擎?理想情况下,我希望能够从如下网址获取 JavaScript:
http://myapp/controller/action.js
我看过 MonoRail 项目,他们似乎有这个功能,但是它非常缺乏文档,而且我找不到任何 ASP.Net MVC 的端口。
编辑:这个想法是能够通过使用如下 url 将页面呈现为标准 HTML:
http://myapp/controller/action
并作为 js(特别是 ExtJS 组件)使用问题中的第一个 url。 Controller 中只有一个操作,但有两个 View :一个用于 HTML,一个用于 JS。
编辑 2: 我基本上想获得与 router extension parsing/request handling 相同的结果在 CakePHP 中。
最佳答案
我想将这个想法扩展到不仅允许 Javascript View ,而且或多或少地允许任何类型的文档。要使用它,只需将 *.js url 的 View 放在 Controller View 文件夹的子文件夹中:
\Views
+-\MyController
+-\js
| +-Index.aspx <- This view will get rendered if you request /MyController/Index.js
+-Index.aspx
该类是任何类型的 ViewEngine 的装饰器,因此您可以将它与 NVelocity/WebForms/Whatever 一起使用:
public class TypeViewEngine<T> : IViewEngine where T : IViewEngine
{
private readonly T baseEngine;
public T BaseEngine
{
get { return baseEngine; }
}
public TypeViewEngine(T baseEngine)
{
this.baseEngine = baseEngine;
}
public void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"TypeViewEngine",
"{controller}/{action}.{type}",
new {controller = "Home", action = "Index", type = "html"}
);
}
public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName)
{
var vars = controllerContext.RouteData.Values;
if(vars["type"] != null && vars["type"].ToString() != "html")
{
viewName = string.Format("{0}/{1}", vars["type"], viewName);
}
return baseEngine.FindView(controllerContext, viewName, masterName);
}
public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName)
{
return baseEngine.FindPartialView(controllerContext, partialViewName);
}
public void ReleaseView(ControllerContext controllerContext, IView view)
{
baseEngine.ReleaseView(controllerContext, view);
}
}
然后,在您的 Global.asax.cs 文件中:
protected void Application_Start()
{
var ve = new TypeViewEngine<WebFormViewEngine>(new WebFormViewEngine());
ve.RegisterRoutes(RouteTable.Routes);
RegisterRoutes(RouteTable.Routes);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(ve);
}
感谢大家对此的帮助!
关于javascript - 是否有支持 JavaScript View 的 ASP.Net MVC View 引擎?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/347918/