Wednesday, June 19, 2019

how to use MVC razer page as Email Template in ASP.Net MVC application?

it is quite useful for code reuse when we implemented the MVC web application. especially we need to support both English and French Template.


we can lay out the template in English and French.

then we can use Razor Engine to load the specific cshtml page by language code

using RazorEngine;
using RazorEngine.Templating;

the following code will utilize the cache mechanism built in the razor engine for better performance.


  var tmplKey =fileNamebyLanuageCode
            if (!Engine.Razor.IsTemplateCached(tmplKey, null))
            {
                var template = GetEmailTemplate(templateName, language);
                Engine.Razor.AddTemplate(tmplKey, template);
                Engine.Razor.Compile(tmplKey, null);
            }

            return Engine.Razor.Run(tmplKey, null, modelData);



  private static string GetEmailTemplate(string templateName, string language)
        {
          
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(templateName))
            {
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }

No comments:

Post a Comment