Hope I can explain my request in a simple way:
In .Net Core, we can display the .cshtml
view, after sending the model data using View(FileName, Model)
.
Is there a way to send the Model
to the .cshtml
file, so that instead of displaying the resulting view I get it emailed a attachment using Mailkit
Thanks to Paris Polyzos and his article.
I found the solution, so liked to share it, may some one get a benefit from it, or improve it.
Firs: We need to create
service
to convert the Rasor into String, the codeRazor2String.cs
is below:Second: We need to add the
"preserveCompilationContext": true
to thebuildOptions
, so theproject.json
become:Third: We need to add the
service
to theConfigureServices
in theStartup
class, so that theStartup.cs
file become:Fourth: Define your
Model
, something likeusers.cs
:Fifth: Create the
View
template, in theViews
folder, something likeViews/Razor2String.cshtml
:Sixth: The
Program.cs
is simply as:Seventh: The main part, 'Email.cs':
If you need the string to be sent back for the browser, you can use:
If you need to send the result to AJAX request, you can use something like:
If you want to have separate method to convert the string into stream like
GenerateStreamFromString(result)
, then you can call it usingusing (Stream stream = GenerateStreamFromString(result)){ }