我有一个IDisposable HTML帮助器来创建我在我的应用中经常需要的特定html结构。我用它剃须刀,它的工作完美
@using (Html.SlidePanel("settings-button"))
{
<span>panel content</span>
}
我有一个基于结构的html助手组件,我想在里面使用我的SlidePanel。
public class MyComponent : IHtmlString
{
private readonly HtmlHelper html;
public MyComponent(HtmlHelper html)
{
this.html = html;
}
public override string ToString()
{
return Render();
}
public string ToHtmlString()
{
return ToString();
}
private string Render()
{
// I want to use my SlidePanel at this place
string renderHtml = "<div>component html</div>";
return renderHtml;
}
}
public static class MyComponentHtmlHelper
{
public static MyComponent MyComponent(this HtmlHelper html)
{
return new MyComponent(html);
}
}
我怎样才能做到这一点?
由于
答案 0 :(得分:0)
您需要拦截SlidePanel通常发送到常规输出的字符串。这样的事情应该有效:
var originalWriter = html.ViewContext.Writer;
using (var stringWriter = new StringWriter())
{
html.ViewContext.Writer = stringWriter;
using (html.SlidePanel())
{
stringWriter.Write("<div>component html</div>");
}
html.ViewContext.Writer = originalWriter;
return stringWriter.ToString();
}
答案 1 :(得分:0)
所以,你去,例如HERE
public static class DisposableExtensions
{
public static IDisposable DisposableDiv(this HtmlHelper htmlHelper)
{
return new DisposableHelper(
() => htmlHelper.BeginDiv(),
() => htmlHelper.EndDiv());
}
public static void BeginDiv(this HtmlHelper htmlHelper)
{
htmlHelper.ViewContext.Writer.Write("<div>");
}
public static void EndDiv(this HtmlHelper htmlHelper)
{
htmlHelper.ViewContext.Writer.Write("</div>");
}
}
}
正如您在示例中看到的“Hello Stranger”放置在附加div
中答案 2 :(得分:0)
感谢Baximilian和StriplingWarrior答案我找到了解决方案
因此解决方案是向SlidePanel类添加第二个构造函数:
public string HtmlString;
public SlidePanel(Func<string> begin, Func<string> content, Func<string> end)
{
this.HtmlString = string.Format("{0}{1}{2}", begin(), content(), end());
}
在SlidePanel Component类中添加公共帮助器
public static string BeginSlidePanel(this HtmlHelper html)
{
return BeginHtml();
}
public static string ContentSlidePanel(this HtmlHelper html, string htmlString)
{
return htmlString;
}
public static string EndSlidePanel(this HtmlHelper html)
{
return EndHtml();
}
然后,我可以像这样使用我的SlidePanel:
new SlidePanel(
() => html.BeginSlidePanel(),
() => html.ContentSlidePanel(GetMyHtmlContent()),
() => html.EndSlidePanel()).HtmlString
非常感谢!