单轨视图组件中的模板
-
03-10-2019 - |
题
是否可以在块组件中使用VM中具有HTML内容的模板?
我在HTML中做了很多事情,并且希望HTML驻留在.vm中,而不是在CodeBehind中。
这是我得到的:
public class TwoColumn : ViewComponent
{
public override void Render()
{
RenderText(@"
<div class='twoColumnLayout'>
<div class='columnOne'>");
// Context.RenderBody();
Context.RenderSection("columnOne");
RenderText(@"
</div>
<div class='columnTwo'>");
Context.RenderSection("columnTwo");
RenderText(@"
</div>
</div>
");
}
}
这是我想要得到的:pagewithtwocolumns.vm:
#blockcomponent(TwoColumn)
#columnOne
One
#end
#columnTwo
Two
#end
#end
twoColumn/default.vm(伪代码):
<div class="twoColumnLayout">
<div class="columnOne">
#reference-to-columnOne
</div>
<div class="columnTwo">
#reference-to-columnTwo
</div>
</div>
解决方案
你有 RenderView
在ViewComponent的基类中的方法。您可以做的是使用将视图定为就地的过载。
只需将此方法贴在您的视图组件中,就应该完成
string RenderViewInPlace(string viewTemplate)
{
var buffer = new StringBuilder();
using (var writer = new StringWriter(buffer))
{
RenderView("myview", writer);
return buffer.ToString();
}
}
其他提示
我终于使用KEN建议的StringWriter技术找到了一个解决方案,但是使用不同的方法。这不是渲染图,它是渲染
public override void Render()
{
PropertyBag["sectionOneText"] = RenderSectionInPlace("sectionOne");
PropertyBag["sectionTwoText"] = RenderSectionInPlace("sectionTwo");
base.Render();
}
public string RenderSectionInPlace(string sectionName)
{
var stringBuilder = new StringBuilder();
Context.RenderSection(sectionName, new StringWriter(stringBuilder));
return stringBuilder.ToString();
}
模板:
<div class="twoColumnLayout">
<div class="columnOne">
$sectionOneText
</div>
<div class="columnTwo">
$sectionTwoText
</div>
</div>
如果您不介意的话,我会建议单轨铁路。能够从视图模板引用该部分很棒:
#render(sectionOne)
不隶属于 StackOverflow