How to render an ASP.NET MVC view as a string?

后端 未结 15 2971
挽巷
挽巷 2020-11-21 04:40

I want to output two different views (one as a string that will be sent as an email), and the other the page displayed to a user.

Is this possible in ASP.NET MVC bet

15条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:17

    I am using MVC 1.0 RTM and none of the above solutions worked for me. But this one did:

    Public Function RenderView(ByVal viewContext As ViewContext) As String
    
        Dim html As String = ""
    
        Dim response As HttpResponse = HttpContext.Current.Response
    
        Using tempWriter As New System.IO.StringWriter()
    
            Dim privateMethod As MethodInfo = response.GetType().GetMethod("SwitchWriter", BindingFlags.NonPublic Or BindingFlags.Instance)
    
            Dim currentWriter As Object = privateMethod.Invoke(response, BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, New Object() {tempWriter}, Nothing)
    
            Try
                viewContext.View.Render(viewContext, Nothing)
                html = tempWriter.ToString()
            Finally
                privateMethod.Invoke(response, BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, New Object() {currentWriter}, Nothing)
            End Try
    
        End Using
    
        Return html
    
    End Function
    

提交回复
热议问题