Can I convert a cshtml file into raw html file? I'm searching for it but couldn't find any good solution.
-
Is the effect in this picture what you want ?buymeacoffee– buymeacoffee2021-12-24 02:12:12 +00:00Commented Dec 24, 2021 at 2:12
-
1No,I want exactly same output as cshtml file.Mahfuzul Islam– Mahfuzul Islam2021-12-24 09:05:23 +00:00Commented Dec 24, 2021 at 9:05
-
Web servers like IIS do that. You do not have to write any code.MB_18– MB_182021-12-29 17:10:58 +00:00Commented Dec 29, 2021 at 17:10
-
Does below answer useful to u ?Ivan Glasenberg– Ivan Glasenberg2021-12-31 01:03:45 +00:00Commented Dec 31, 2021 at 1:03
Add a comment
|
1 Answer
Found this solution a few months ago at SO.
public class CustomViewRendererService
{
private readonly IRazorViewEngine _razorViewEngine;
private readonly ITempDataProvider _tempDataProvider;
public CustomViewRendererService(
IRazorViewEngine razorViewEngine,
ITempDataProvider tempDataProvider)
{
_razorViewEngine = razorViewEngine;
_tempDataProvider = tempDataProvider;
}
public async Task<string> RenderViewToStringAsync(ControllerContext actionContext, string viewPath,
object model)
{
var viewEngineResult = _razorViewEngine.GetView(viewPath, viewPath, false);
if (viewEngineResult.View == null || (!viewEngineResult.Success))
{
throw new ArgumentNullException($"Unable to find view '{viewPath}'");
}
var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), actionContext.ModelState);
viewDictionary.Model = model;
var view = viewEngineResult.View;
var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider);
using var sw = new StringWriter();
var viewContext =
new ViewContext(actionContext, view, viewDictionary, tempData, sw, new HtmlHelperOptions());
await view.RenderAsync(viewContext);
return sw.ToString();
}
}
Using inside controller:
const string templatePath = "~/Views/Email/Test.cshtml";
string msg = await _viewService.RenderViewToStringAsync(ControllerContext, templatePath, new EmailConfirmationBuilderViewModel(url));