Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rendered source code of an html page from code behind so I can send it in mail

Tags:

html

asp.net

I created an aspx page wit a button send. on that button click a function code behind goes on. What I want is that when I click on the button to get all the html source code rendered of the aspx page in a variable so I can send it in a mail. how can I get the rendered html source code from code behind function.

like image 867
hassan sleh Avatar asked Dec 14 '25 01:12

hassan sleh


1 Answers

I actually just wrote a method for this not too long ago. It gets the view at a provided relative path, passes in a provided model, and renders the view as a string.

public static string RenderViewToString(string relativePathToControl, object viewData)
{
    ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };

    viewPage.ViewData = new ViewDataDictionary(viewData);
    viewPage.Controls.Add(viewPage.LoadControl(relativePathToControl));

    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        using (HtmlTextWriter tw = new HtmlTextWriter(sw))
        {
            viewPage.RenderControl(tw);
        }
    }

    return sb.ToString();
}

You may need to add a few using statements.

like image 148
Charmander Avatar answered Dec 15 '25 15:12

Charmander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!