Skip to main content

Posts

Showing posts from January, 2017

MVC Render Partial View to HTML inside controller

We know that we can use @Html.Partial("PartialViewName") to render partial view in view. However, sometimes we need to render the partial view to HTML inside the controller. For example, I have a ChoiceResultsPartial which displays the choices that user has made. I also want to send the results to the email address the user provides. The best way to achieve this is to use the same way as @Html.Partial() to get the HTML and send the HTML as email body. In order to achieve this, we can use following code:         public string RenderViewToString( string viewName, object model, TempDataDictionary tempData)         {             if ( string .IsNullOrEmpty(viewName))                 viewName = this .ControllerContext.RouteData.GetRequiredString( "action" );             var viewData = new ViewDataDictionary(model);             using ( var sw = new StringWriter ())             {                 var viewResult = ViewEngines .Engines.FindPartialView(this.Control