我正致力于将自动CoffeeScript编译集成到ASP.NET MVC项目中。如果您在脚本标记中指定一个.coffee文件,它就会将其编译成服务器上的javascript。
我希望能够对嵌入在视图中的CoffeeScript进行同样的操作。是否有可能编写一个不同类型的HtmlHelper,使我能够捕获用户在using块中提供的内容,类似于Html.BeginForm使用IDispose的方式?
发布于 2011-06-30 20:54:53
Html.BeginForm()实际上并不捕获using
块的内容。它只是用form标记包围它,方法是从Dispose
方法中从IDisposable
编写开始标记,然后将结束标记写到响应上。
请参阅Html.BeginForm()
的实现这里和Dispose方法这里。
如果实际上希望捕获块的内容,则可能需要编写一个将剃刀模板作为参数的助手方法。
通过实现以下方法:
public static class HtmlHelperExtensions
{
public static string CoffeeScript(this HtmlHelper htmlHelper, Func<HelperResult> template)
{
// Then you can access the contents of the block here
string contents = template().ToHtmlString();
return DoSomething(string);
}
}
您可以在Razor视图中使用它,如:
@Html.CoffeeScript(@<text>
Anything can go here
</text>;);
更新:只是为了澄清,考虑到扩展方法属于MyApplication.Extensions
命名空间,您应该将以下内容添加到视图的顶部:
@using MyApplication.Extensions;
https://stackoverflow.com/questions/6529968
复制