Download View instead of displaying it

Asked

Viewed 82 times

1

there is some way that instead of me returning a view and displaying it on the screen for the user, I return it but instead of displaying it I save the file . html on the computer? The code is as follows::

return View("~/Views/Item/Item.cshtml", model);

but it returns the view and displays it to the user, I wanted a way to download the html file instead of displaying it, it is possible to do this somehow?

1 answer

2


public string RenderRazorViewToString(string viewName, object model)
{
   ViewData.Model = model;
   using (var sw = new StringWriter())
   {

    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,viewName);
    var viewContext = new ViewContext(ControllerContext, 
                                 viewResult.View,
                                 ViewData, 
                                 TempData, 
                                 sw);

    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);

    return sw.GetStringBuilder().ToString();

  }
}

and in your controller:

return File(encoding.GetBytes(RenderRazorViewToString("Item", model)),"text/html");

I may have to change the name of path (path) for it to work, make a debug if it doesn’t work, and see which one path is looking for the View which has been passed as a parameter.

  • Thanks, it worked :D

  • You’re welcome! Ja now, Virgilio, why did you edit the answer? Can’t you write in Portuguese from Portugal? Can’t I treat a person for you? curiosity...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.