开发者

Create html helper similar to BeginForm where you can gain access to the content of the block server-side

I am working on integrating automatic CoffeeScript compilation inside ASP.NET MVC projects. I already have the piece working where if you specify a .coffee file i开发者_运维知识库n a script tag, it compiles it to javascript on the server.

I want to be able to do the same for CoffeeScript embedded in a view. Is it possible to write an HtmlHelper of some variety that would allow me to capture the content the user supplies within the using block similar to how Html.BeginForm works using IDispose?


Html.BeginForm() doesn't actually capture the contents of the using block. It just surrounds it with the form tag, by writing the opening tag and then the closing tag to the response on the Dispose method, from IDisposable.

Please see Html.BeginForm()'s implementation here, and the Dispose method here.

If you actually want to capture the contents of the block, you might want to write a helper method that takes a Razor Template as a parameter.

By implementing the following method:

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);
    }
}

You can use it in you Razor view like this:

@Html.CoffeeScript(@<text>
    Anything can go here
</text>;);

UPDATE: Just to clarify, given your extension method belongs to the MyApplication.Extensions namespace, you should add the following to the top of your view:

@using MyApplication.Extensions;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜