Skip to main content

Posts

Showing posts from January, 2015

In MVC3 Razor, how do I get the html of a rendered view inside an action?

I use a static method in a class I called  Utilities.Common  I pass views back to the client as properties of JSON objects constantly so I had a need to render them to a string. Here ya go: public static string RenderPartialViewToString ( Controller controller , string viewName , object model ) { controller . ViewData . Model = model ; using ( StringWriter sw = new StringWriter ()) { ViewEngineResult viewResult = ViewEngines . Engines . FindPartialView ( controller . ControllerContext , viewName ); ViewContext viewContext = new ViewContext ( controller . ControllerContext , viewResult . View , controller . ViewData , controller . TempData , sw ); viewResult . View . Render ( viewContext , sw ); return sw . ToString (); } } This will work for full views as well as partial views, just change  ViewEngines.Engines.FindPartialView  to  ViewEngines.Engines.FindView . FindView needs another parameter (

How to download .xslx File from server using EPPlus and MVC - stream Response

All you need to do is reset the stream position.  stream.Position = 0; You  shouldn't write directly to the Response , it's not the MVC way. It doesn't follow the correct MVC pipeline and it tightly couples your controller action code to the Response object. When you add a file name as the 3rd parameter in  File() , MVC automatically adds the correct  Content-Disposition  header... so you shouldn't need to add it manually. The short of it is, this is what you want: public ActionResult Index () { using ( ExcelPackage package = new ExcelPackage ()) { // I populate the worksheet here. I'm 90% sure this is fine // because the stream file size changes based on what I pass to it. var stream = new MemoryStream (); package . SaveAs ( stream ); string fileName = "myfilename.xlsx" ; string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&qu