Rendering a Spark Partial View to a string

by Guido Tapia

in software-engineering,

September 25, 2009

I needed to do this recently so I searched the interweb and quickly found this great article by Brent Edwards:

Now don’t get me wrong, this works and is explained very well but I don’t see the point in re-creating the ViewEngine? So I cleaned this up and ended up with:

public static string GetPartialViewHtml(ViewDataDictionary viewData, string viewRalativePath) {
  SparkViewFactory f = (SparkViewFactory) ViewEngines.Engines.First(e => e is SparkViewFactory);
  SparkView view = (SparkView) f.Engine.CreateInstance(f.CreateDescriptor(null, null, viewRalativePath, null, false));
  view.ViewData = viewData;
  StringWriter writer = new StringWriter();
  return writer.ToString();

Done, now for anyone that has tried to do this with ASP.Net MVC View engine, I pity you.


Guido Tapia Software Development Manager PicNet Pty Ltd