Rendering a Spark Partial View to a string

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

http://blog.edwardsdigital.com/post/Rendering-a-Spark-partial-view-to-a-string-or-JSONP-with-ASPNET-MVC.aspx

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();
  view.RenderView(writer);
  return writer.ToString();
}

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

Thanks

Guido Tapia
Software Development Manager
PicNet Pty Ltd

Uncategorized

About The Author

Guido Tapia

Chief Technology Officer – Software Development. Guido has led the development of Enterprise Risk Management system Risk Shield and the award winning web application, Mouse Eye Tracking - a usability tool that reveals website visitor activity. In addition has led numerous software projects for blue chip Australian organisations and specialises in Java, .Net and Javascript development.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>