Antaris RazorEngine v3.9.3在ASP.NET MVC4控制器中用于创建表单元素。 在结果中,html输入元素呈现在表单元素之外。 例如
@using (Html.BeginForm("Test", "Upload"))
{
<input type="file" />
<input type="submit"/>
}
产生
<form action="/Upload/Test" method="post"></form>
<input type="file" />
<input type="submit"/>
虽然正确的结果应该是
<form action="/Upload/Test" method="post">
<input type="file" />
<input type="submit"/>
</form>
RenderScript仅返回输入元素。 <form action="/Upload/Test" method="post">
直接写入输出。看起来像BeginForm()直接写入视图,而Razorengine不捕获其输出。
如何解决这个问题?
查看:
@Model.RenderScript()
型号:
public IHtmlString RenderScript() {
var config = new TemplateServiceConfiguration();
config.BaseTemplateType = typeof(HtmlTemplateBase<>);
config.Namespaces = new HashSet<string>(new string[] {
"System",
"System.Collections",
"System.Collections.Generic",
"System.Globalization",
"System.Linq",
"System.Web",
"System.Web.Mvc",
"System.Web.Mvc.Html"
});
razor = RazorEngineService.Create(config);
// In real application colModel is retrieved from database
var colModel=@"
@using (Html.BeginForm(""Test"", ""Upload""))
{
<input type='file' />
<input type='submit'/>
}
";
string res = razor.RunCompile(colmodel, colmodel, typeof(object), new object());
return MvcHtmlString.Create(res);
}
模板基类:
using RazorEngine.Templating;
using RazorEngine.Text;
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
public class HtmlTemplateBase<T> : TemplateBase<T>, IViewDataContainer
{
// http://stackoverflow.com/questions/8561164/razorengine-issues-with-html
HtmlHelper<T> helper = null;
ViewDataDictionary viewdata = null;
public HtmlHelper<T> Html
{
get
{
// https://github.com/Antaris/RazorEngine/issues/150
if (helper == null)
{
var p = WebPageContext.Current;
var wvp = p.Page as WebViewPage;
var context = wvp != null ? wvp.ViewContext : null;
context.Writer = this.CurrentWriter;
helper = new HtmlHelper<T>(context, this);
}
return helper;
}
}
public ViewDataDictionary ViewData
{
get
{
if (viewdata == null)
{
viewdata = new ViewDataDictionary();
viewdata.TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = string.Empty };
if (this.Model != null)
{
viewdata.Model = Model;
}
}
return viewdata;
}
set
{
viewdata = value;
}
}
public override void WriteTo(TextWriter writer, object value)
{
if (writer == null)
throw new ArgumentNullException("writer");
if (value == null) return;
//try to cast to RazorEngine IEncodedString
var encodedString = value as IEncodedString;
if (encodedString != null)
{
writer.Write(encodedString);
}
else
{
var htmlString = value as IHtmlString;
if (htmlString != null) writer.Write(htmlString.ToHtmlString());
else
{
encodedString = TemplateService.EncodedStringFactory.CreateEncodedString(value);
writer.Write(encodedString);
}
}
}
}
中发布