Skip to content

Instantly share code, notes, and snippets.

@bhameyie
Last active April 16, 2020 05:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhameyie/6314781 to your computer and use it in GitHub Desktop.
Save bhameyie/6314781 to your computer and use it in GitHub Desktop.
An extension to render view as string with NancyFx
using System.IO;
using Nancy;
using Nancy.ViewEngines;
namespace Web.Modules
{
public static class ModuleExtensions
{
public static string RenderRazorViewToString(this NancyModule module, string viewName, object model)
{
return RenderRazorViewToString(module, viewName, model, module.ModulePath);
}
public static string RenderRazorViewToString(this NancyModule module, string viewName, object model, string modulePath)
{
using (var stream = new MemoryStream())
{
var viewLocationContext = new ViewLocationContext { Context = module.Context, ModulePath = modulePath };
module.ViewFactory.RenderView(viewName, model, viewLocationContext).Contents.Invoke(stream);
var streamWriter = new StreamWriter(stream);
streamWriter.Flush();
stream.Position = 0;
var streamReader = new StreamReader(stream);
return streamReader.ReadToEnd();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment