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>)
}
答案 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>
}