MVC 3 Razor, Helpers with custom markup/section

前端 未结 4 581
囚心锁ツ
囚心锁ツ 2021-02-05 21:16

I\'m not even sure if this is possible, but I thought I would check to see if there is any way to make this easier.

First, I have some repeated markup in my site that lo

4条回答
  •  情书的邮戳
    2021-02-05 21:33

    @TheKaneda, Thanks for the insight. I took your idea and extended it, such that you supply a PartialView name and it knows how to parse it.

     _
    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
    

    Use the same usage as @TheKaneda's example. In your partial view, instead of calling @RenderBody(), just put @@RenderBody() which acts as a flag for the middle part of your content. Sorry for the VB translation.

    Uses an example of my usage.

    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
    

    My Partial looks like this...

    @@RenderBody()

提交回复
热议问题