ASP.NET MVC Email

后端 未结 7 1098
日久生厌
日久生厌 2021-01-30 11:50

Is their a solution to generate an email template using an ASP.NET MVC View without having to jump through hoops.

Let me elaborate jumping through hoops.



        
7条回答
  •  隐瞒了意图╮
    2021-01-30 12:34

    Try using spark view engine (http://www.sparkviewengine.com/). It is easy to use, nicer than standard engine and doesn't require to fake context.

    You can also use function from this answer Render a view as a string , but it requires faking context. This is the way standard view engine works and you can do nothing about that.

    This is my extension class that is used to generate views to string. First is for standard view engine, second for Spark:

    public static class ControllerHelper
    {
        /// Renders a view to string.
        public static string RenderViewToString(this Controller controller,
                                                string viewName, object viewData)
        {
            //Getting current response
            var response = HttpContext.Current.Response;
            //Flushing
            response.Flush();
    
            //Finding rendered view
            var view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName).View;
            //Creating view context
            var viewContext = new ViewContext(controller.ControllerContext, view,
                                              controller.ViewData, controller.TempData);
    
            //Since RenderView goes straight to HttpContext.Current, we have to filter and cut out our view
            var oldFilter = response.Filter;
            Stream filter = new MemoryStream(); ;
            try
            {
                response.Filter = filter;
                viewContext.View.Render(viewContext, null);
                response.Flush();
                filter.Position = 0;
                var reader = new StreamReader(filter, response.ContentEncoding);
                return reader.ReadToEnd();
            }
            finally
            {
                filter.Dispose();
                response.Filter = oldFilter;
            } 
        }
    
        /// Renders a view to string.
        public static string RenderSparkToString(this Controller controller,
                                                string viewName, object viewData)
        {
            var view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName).View;
            //Creating view context
            var viewContext = new ViewContext(controller.ControllerContext, view,
                                              controller.ViewData, controller.TempData);
    
            var sb = new StringBuilder();
            var writer = new StringWriter(sb);
    
            viewContext.View.Render(viewContext, writer);
            writer.Flush();
            return sb.ToString();
        }
    }
    

提交回复
热议问题