创建助手来缩小JS;我究竟做错了什么?

时间:2012-02-18 23:29:19

标签: c# javascript asp.net asp.net-mvc razor

public class JavaScriptHelper
{
    public HelperResult Minify(Func<HelperResult> code)
    {
        return new HelperResult(writer => writer.Write(JavaScriptCompressor.Compress(code().ToString())));
    }
}

@section Script
{
@JavaScriptHelper.Minify(
@<script>
    (function ($, b) {
        $(function () {
            $("#upload").bind("submit", function (e) {
                e.preventDefault();
                console.log("going");
                $(this).ajaxSubmit(function (result) {
                    if (!b.ajaxFailure(result, true)) {
                        console.log(result);
                    }
                });
            });
        });
    })(jQuery, b);
</script>)
}

1 个答案:

答案 0 :(得分:1)

帮助者需要是静态的,Razor将传递Func<dynamic, HelperResult>而不仅仅是Func<HelperResult>。此外,您不希望将<script></script>传递给minifier,因此将它们移到JavaScriptHelper.Minify(...)调用之外,然后用<text></text>包装内容,以便Razor知道如何解析它。试试这个:

public class JavaScriptHelper
{
        public static HelperResult Minify(Func<dynamic, HelperResult> code)
        {
            return new HelperResult(writer => writer.Write(JavaScriptCompressor.Compress(code(null).ToString())));
        }
}

@section Script
{
    <script>
    @JavaScriptHelper.Minify(
    @<text>
    (function ($, b) {
        $(function () {
            $('#upload').bind('submit', function (e) {
                e.preventDefault();
                console.log('going');
                $(this).ajaxSubmit(function (result) {
                    if (!b.ajaxFailure(result, true)) {
                        console.log(result);
                    }
                });
            });
        });
    })(jQuery, b);

    </text>)
    </script>

}