1

I'm working on a WPF application that needs to populate HTML templates and save them to the disk.

Ideally I could use an MVC project to do this, e.g. define a View and pass a ViewModel to it, and then write the output to a FileStream rather than the Response stream.

Unfortunately there's no guarantee of internet access so I can't host it on a remote server, and there's no guarantee of a local web server either, so I have nowhere to host it.

Is there any way for me to do this in WPF or to get an MVC project (that I can reference from the WPF solution) to work outside the context of a web server?

Or should I take a different approach?

DaveDev
  • 41,155
  • 72
  • 223
  • 385
  • 1
    You could look into [runtime T4 templates](http://msdn.microsoft.com/en-us/library/vstudio/ee844259.aspx), that's what I'm using to generate HTML mails. – Patryk Ćwiek Jun 27 '13 at 10:41
  • More or less duplicate of this question? http://stackoverflow.com/questions/14243296/whats-the-current-best-solution-for-generating-html-from-asp-net-razor-template – Rune Grimstad Jun 27 '13 at 10:42
  • The question is of a similar theme, but I don't think it's a duplicate. The question you refer to specifies a console application, so they're looking to generate the HTML template purely through C#. I'm looking to define the template in text and populate it with C# in a WPF application. – DaveDev Jun 27 '13 at 10:59

1 Answers1

1

The solution is to use RazorEngine

E.g.:

public static string RenderPartialViewToString(string templatePath, string templateName, object viewModel)
{
    string text = File.ReadAllText(Path.Combine(templatePath, templateName));


    string renderedText = Razor.Parse(text, viewModel);
    return renderedText;
}

in this case, templateName is a .cshtml file that contains the following Html & Razor code:

<div>        
    <h1>Age: @Model.Age</h1>
    <input type="button" value="Just a Sample Button" />
</div>

and viewModel is simply an anonymous object defined as

var anonObj = new
{
    Age = 10,
};

Razor.Parse() does the magic of parsing the contents of templateName and replacing the inline C# with values in the HTML.

DaveDev
  • 41,155
  • 72
  • 223
  • 385