【问题标题】:Convert Razor View to string ASP.NET core [duplicate]将 Razor 视图转换为字符串 ASP.NET 核心 [重复]
【发布时间】:2019-10-05 12:43:40
【问题描述】:

我想将视图作为电子邮件正文发送,我正在使用 sendgrid。 如何将视图转换为字符串?

我在这里得到了一个代码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);
            }
        }


这一行说空引用错误

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

【问题讨论】:

    标签: c# asp.net-core sendgrid-templates


    【解决方案1】:

    试试RazorLight library

    IRazorLightEngine engine = EngineFactory.CreatePhysical("PhysicalToView"); 
    
    var model = new model
    { 
    
       BookTitle = "Book Title", 
       Price= 5.65
     }; 
    
     string result = engine.Parse("templateName.cshtml", model); 
    

    物理html代码

    <h2>@Model.BookTitle, </h2>      
    <h1>@Model.Price</h1> 

    【讨论】:

      猜你喜欢
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      相关资源
      最近更新 更多