Set 'cshtml' data and return a string

2019-06-14 11:04发布

I have a confirmation email template .cshtml as following:

<html> 
    <head>
        <title>company name: Email Verification - Action Required</title> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head> 
    <body> 
            Thanks for signing up for company name!
            <br/>
            <br/>

            Thank you for signing up to company name. Please press the link below to confirm your email address <br/>
            If you did not sign up for company name, please ignore this email, and accept our apologies for the inconvenience.

            <br/>
            <br/>

            <a href="@Model.ConfirmLink">@Model.ConfirmLink</a>

            <br/>
            <br/>
            <br/>

            Thanks,<br/>
            The <a href="http://company name.com" >company name</a> Team                       
        </table>
    </body>
</html>

Is there a mechanism I can set data (@Model.ConfirmLink) and get back a result as string? (not manually replace string)

标签: c# razor
2条回答
Emotional °昔
2楼-- · 2019-06-14 11:23

Yes, you can use Razor as template engine for emails.

I use this class.

public static class EmailFactory
{
    public static string ParseTemplate<T>(T model, string templatesPath, EmailType emailType)
    {
        string templatePath = Path.Combine(templatesPath, string.Format("{0}.cshtml", emailType));
        string content = templatePath.ReadTemplateContent();

        return Razor.Parse(content, model);
    }
}
  • templatesPath - is the path where my cshtml views for email are.
  • EmailType is and enum that has elements that are the same as the view namse from the templatesPath directory.

The essence is Razor.Parse(content, model); it takes a string that is a valid razor view and a model and merges them together. Same as the views in ASP MVC.

查看更多
你好瞎i
3楼-- · 2019-06-14 11:35

You can use RazorEngine, which uses the same syntax as Razor does, but gives you the ability to render the text without the need of ASP.NET MVC.

How your code would work:

string template = yourHtmlCodeAsString;
string result = Razor.Parse(template, new { ConfirmLink = "http://.../" });

You can load that template string from a file, a resource, etc.

查看更多
登录 后发表回答