How do you convert a Razor view to a string?

前端 未结 2 1888
终归单人心
终归单人心 2021-02-05 19:19

I would like to use my Razor view as some kind of template for sending emails, so I would like to \"save\" my template in a view, read it into controller as a string, do some ne

2条回答
  •  独厮守ぢ
    2021-02-05 19:45

    Take a look at the RazorEngine library, which does exactly what you want. I've used it before for email templates, and it works great.

    You can just do something like this:

    // Read in your template from anywhere (database, file system, etc.)
    var bodyTemplate = GetEmailBodyTemplate();
    
    // Substitute variables using Razor
    var model = new { Name = "John Doe", OtherVar = "Hello!" };
    var emailBody = Razor.Parse(bodytemplate, model);
    
    // Send email
    SendEmail(address, emailBody);
    

提交回复
热议问题