您可以嘗試RazorEngine以允許執行剃鬚刀中的字符串模板。
例如,從項目選址http://antaris.github.io/RazorEngine/示例代碼:
using RazorEngine;
using RazorEngine.Templating; // For extension methods.
string template = "Hello @Model.Name, welcome to RazorEngine!";
var result =
Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });
但是有,HTML和Url傭工在MVC框架中定義的,一個抓因此它默認是不支持的。
我會建議您嘗試通過傳遞模型來創建您的模板,以便您不必使用@ Html.Action。
如果無法避免,則有可能被其他建議的解決方案,以便回答https://stackoverflow.com/a/19434112/2564920:
[RequireNamespaces("System.Web.Mvc.Html")]
public class HtmlTemplateBase<T>:TemplateBase<T>, IViewDataContainer
{
private HtmlHelper<T> helper = null;
private ViewDataDictionary viewdata = null;
public HtmlHelper<T> Html
{
get
{
if (helper == null)
{
var writer = this.CurrentWriter; //TemplateBase.CurrentWriter
var context = new ViewContext() { RequestContext = HttpContext.Current.Request.RequestContext, Writer = writer, ViewData = this.ViewData };
helper = new HtmlHelper<T>(vcontext, 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
{
//try to cast to IHtmlString (Could be returned by Mvc Html helper methods)
var htmlString = value as IHtmlString;
if (htmlString != null) writer.Write(htmlString.ToHtmlString());
else
{
//default implementation is to convert to RazorEngine encoded string
encodedString = TemplateService.EncodedStringFactory.CreateEncodedString(value);
writer.Write(encodedString);
}
}
}
}
然後,你必須使用HtmlTemplateBase(上https://antaris.github.io/RazorEngine/TemplateBasics.html#Extending-the-template-Syntax改裝基地):
var config = new TemplateServiceConfiguration();
// You can use the @inherits directive instead (this is the fallback if no @inherits is found).
config.BaseTemplateType = typeof(HtmlTemplateBase<>);
using (var service = RazorEngineService.Create(config))
{
string template = "<h2> Welcome To Page </h2> <br/> @Html.Action(\"actionName\", \"controllerName\")";
string result = service.RunCompile(template, "htmlRawTemplate", null, null);
}
實質上,它告訴RazorEngine使用涉及mvc的基本模板,以便可以使用Html和Url助手。
如果你想在視圖中的鏈接,那麼你的字符串需要包含''標籤(不是剃鬚刀代碼) –
您好,謝謝您的回覆。我想調用我的字符串內的控制器的操作方法。請參閱問題 –
上面提到的示例。您不能。 '@ Html.Raw()'不執行剃鬚刀代碼,它只是呈現輸出。 –