@TheKaneda,谢谢你的见解。我把你的想法和扩展它,这样你就提供了一个PartialView名称,它知道如何解析它。
<Extension()> _
Public Function UseTemplate(ByVal html As HtmlHelper, ByVal PartialView As String) As IDisposable
Return New TemplateWrapper(html, PartialView)
End Function
Public Class TemplateWrapper
Implements IDisposable
Private _HtmlHelper As HtmlHelper
'Index 0 is header
'Index 1 is footer
Private _TemplateWrapper As String()
Public Sub New(ByVal Html As HtmlHelper, ByVal PartialView As String)
_TemplateWrapper = Html.Partial(PartialView).ToHtmlString.Split("@@RenderBody()")
_HtmlHelper = Html
_HtmlHelper.ViewContext.Writer.Write(_TemplateWrapper(0))
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
_HtmlHelper.ViewContext.Writer.Write(_TemplateWrapper(1).Substring(12))
End Sub
End Class
使用与@ TheKaneda示例相同的用法。在你的局部视图中,不要调用@RenderBody(),只需将@@ RenderBody()作为内容中间部分的标志。对不起VB翻译。
使用我的用法的一个例子。
Using Html.UseTemplate("ContentWrapper")
@Html.EditorFor(Function(m) m.Var1, "TemplateHint")
@Html.EditorFor(Function(m) m.Var2, "TemplateHint")
@Html.EditorFor(Function(m) m.Var3)
End Using
我的部分看起来像这样...
<div class="content">
@@RenderBody()
</div>
这正是我一直在寻找的。 – Josh 2012-02-01 14:02:10
有一个简单的例子在http://stackoverflow.com/questions/7196276/creating-mvc3-razor-helper-like-helper-beginform – 2013-03-07 11:14:27
我很难看到是什么使它更简单,考虑到解决方案正是相同......在这个例子中,唯一的附加代码就是为了满足问题的要求 - 还有一个基本的检查,以避免Dispose的副作用被两次调用。 – JimmiTh 2013-03-07 12:07:50