Click here to Skip to main content
15,899,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I want to make a method which received action and controller name as a string and execute that action of the controller and get the result as a string e.g like RenderAction helper method do in Razor.

What I am trying to do.

C#
public static string RenderViewAsString(string ActionName, string ControllerName, object model)
{
//calling the action and returning the result.
}



The method that I am currently using:

C#
protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

This method is just taking viewname and object model, but it will also required the ControllerContext. As I am using it in BLL so every time i run it, it give me
C#
ControllerContext = null


I want to make a method that just take action name and controller name with model for the view and return me the string for the email body, without using each time the same method in every controller.

If I used current method in my controller then it will work properly as ControllerContext is set and the view is in the controller directory. But, what if i want to use a view multiple time from multiple controller and also to send email method from multiple controller.

What I have tried:

I have searching on the internet not find anything specific related to my question. But just the method that I am using currently.
Posted
Updated 6-Aug-16 1:59am
v2
Comments
njammy 5-Aug-16 5:36am    
Please update your question with any code you have written already which wants to call "RenderViewAsString" method.
deepankarbhatnagar 5-Aug-16 11:50am    
What you have tried... please show your code..
Member 10992268 6-Aug-16 6:42am    
Please update your question
Shahzad Mirza 6-Aug-16 7:59am    
question updated.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900