-2

I want to send a view as email body, i'm using sendgrid. How do i convert view to string ?

I got a code here https://long2know.com/2017/08/rendering-and-emailing-embedded-razor-views-with-net-core/


public string RenderToString<TModel>(string viewPath, TModel model)
        {
            try
            {
                var viewEngineResult = _viewEngine.GetView("Views/", viewPath, false);

                if (!viewEngineResult.Success)
                {
                    throw new InvalidOperationException($"Couldn't find view {viewPath}");
                }

                var view = viewEngineResult.View;

                using (var sw = new StringWriter())
                {
                    var viewContext = new ViewContext()
                    {
                        HttpContext = _httpContextAccessor.HttpContext ?? new DefaultHttpContext { RequestServices = _serviceProvider },
                        ViewData = new ViewDataDictionary<TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model },
                        Writer = sw
                    };
                    view.RenderAsync(viewContext).GetAwaiter().GetResult();
                    return sw.ToString();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error ending email.", ex);
            }
        }


This line say nullreference error

view.RenderAsync(viewContext).GetAwaiter().GetResult();

1 Answers1

0

Try RazorLight library

IRazorLightEngine engine = EngineFactory.CreatePhysical("PhysicalToView"); 

var model = new model
{ 

   BookTitle = "Book Title", 
   Price= 5.65
 }; 

 string result = engine.Parse("templateName.cshtml", model); 

Physical html Code

<h2>@Model.BookTitle, </h2>      
<h1>@Model.Price</h1> 
Black
  • 65
  • 7