2
I have the following code:
PDFController Ctrl = new PDFController();
byte[] ArquivoPDF = Ctrl.GerarPDF(xml);
This part above is in the Webapi, where I create a new instance of the Controller to use the function that is in it. The code below is already part of the controller:
public class PDFController : Controller
{
public string RenderizaHtmlComoString(string NomeView, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, NomeView);
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();
}
}
}
But in the part that I will form the variable viewResult, it gives an error and says that the Controllercontext cannot be null. Can someone help me? *This Controller is not linked to any View.
I get it, but in case I need to call these controller functions from within an Api, would you know how to do that? was even for that reason that I created an instance of the controller, to try to do with q I managed to call the method.
– Brayan
Actually in this case are controllers of different types. In this case I would put this method in a separate class to be used in the controller. I don’t know how the code is, so I don’t know if it’s possible because of some dependency.
– André Luis Marmo
So what’s stopping me is that this PDF q method I posted, it returns a view, only, I can even return the view even outside the controller, only it contains some Tempdata and some Viewbag for its assembly to be complete. Then I find another problem, that I did not find a way to use the Tempdata and Viewbag outside the controller... Unless you have some way to replace them with other options I’ve never heard of.
– Brayan
Well I really think you have a problem with architecture there... this method is very attached to an environment, which in this case is the web since Temdata and Viewbag are usually used to pass information to view. In this case requires further analysis to decouple it and separate it into a class responsible for it, principle of sole responsibility (SOLID).
– André Luis Marmo
Yeah, you’re in a little bit of a bind, it’s just that I already had this awareness that I was going to have to move the structure, but I was hoping that there was some way that it wasn’t necessary to make these changes, but thank you I will begin to study the structure to make the adjustments. Thank you :D
– Brayan
Good luck there, and with calm you can separate it for sure. ;)
– André Luis Marmo