0

Can I convert a cshtml file into raw html file? I'm searching for it but couldn't find any good solution.

4
  • Is the effect in this picture what you want ? Commented Dec 24, 2021 at 2:12
  • 1
    No,I want exactly same output as cshtml file. Commented Dec 24, 2021 at 9:05
  • Web servers like IIS do that. You do not have to write any code. Commented Dec 29, 2021 at 17:10
  • Does below answer useful to u ? Commented Dec 31, 2021 at 1:03

1 Answer 1

3
+100

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.