我正在使用Handlebarsjs构建模板。我的UI提供了编辑器,用户可以在其中编辑模板。在客户端,我想预编译模板,并使用Jquery Ajax将其保存在服务器上。服务器端是ASP.NET Core MVC
假设用户已经创作了以下模板
<script id="entry-template" type="text/x-handlebars-template">
<div>whatever {{ name }}</div>
</script>
在“保存”按钮上,单击“我具有以下代码以预编译模板并将其保存到服务器”。
$("#btnSave").click(function () {
var source = $("#entry-template").html();
var str = Handlebars.precompile(source);
$.post("/home/save", JSON.stringify(str))
});
Handlebars.precompile方法以字符串形式返回javascript函数。像下面一样
"{"compiler":[7,">=
4.0.0"],"main":function(container,depth0,helpers,partials,data) {
var helper;
return "\n <div>whatever "
+ container.escapeExpression(((helper = (helper = helpers.name || (depth0 !=
null ? depth0.name : depth0)) != null ? helper : helpers.helperMissing),
(typeof helper === "function" ? helper.call(depth0 != null ? depth0 :
(container.nullContext || {}),{"name":"name","hash":{},"data":data}) :
helper)))
+ "</div>\n";
},"useData":true}"
但是,ASP.NET Core MVC返回错误
ArgumentException:键'“ {\” compiler \“:[7,\”>'是无效的JQuery 语法,因为它缺少右括号。参数名称:键 Microsoft.AspNetCore.Mvc.ModelBinding.JQueryKeyValuePairNormalizer.NormalizeJQueryToMvc(StringBuilder 生成器,字符串键) Microsoft.AspNetCore.Mvc.ModelBinding.JQueryKeyValuePairNormalizer.GetValues(IEnumerable> originalValues,int valueCount) Microsoft.AspNetCore.Mvc.ModelBinding.JQueryFormValueProviderFactory.AddValueProviderAsync(ValueProviderFactoryContext 上下文) Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.CreateAsync(ActionContext actionContext,IList工厂) Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.CreateAsync(ControllerContext controllerContext) Microsoft.AspNetCore.Mvc.Internal.ControllerBinderDelegateProvider + <> c__DisplayClass0_0 +
d.MoveNext() Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext 上下文)Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref 状态下一个,ref Scope范围,ref对象状态,ref bool isCompleted) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext 上下文) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)
ASP.NET控制器
[HttpPost]
public IActionResult Save([FromBody]string str)
{
PreCompiledScript = str;
return Ok();
}