2 years ago

#51406

test-img

kosnkov

how to generate html from cshtml

I need to validate if html has more then single h1 tag. My project is mvc cshml razor files which requrires models.

How to generate full html from cshtml and mockup models ? It that possible with Rosylyn ?

I tried this way but i still can't render paritals inside what I want to achive it end html with all partials in cshtml rendered

var ws = MSBuildWorkspace.Create();

            // Store the translation keys...

            string solutionRoot = @"C:\src\";
            string sln = solutionRoot + "website.sln";

            // Load the solution, and find all the cshtml Razor views...
            var solution =  ws.OpenSolutionAsync(sln).GetAwaiter().GetResult();
            var projects = solution.Projects;
            var mainProj = solution.Projects.Where(x => x.Name == "Portal").Single();
            FileInfo[] cshtmls = new DirectoryInfo(solutionRoot).GetFiles("*.cshtml", SearchOption.AllDirectories);

            //// Go through each Razor View - generate the equivalent CS and add to the project for compilation.
            var host = new RazorEngineHost(RazorCodeLanguage.Languages["cshtml"]);
            var razor = new RazorTemplateEngine(host);
            var cs = new CSharpCodeProvider();
            var csOptions = new CodeGeneratorOptions();
            foreach (var cshtml in cshtmls.Where(x=>x.Name.Contains("Index")))
            {
                using (StreamReader re = new StreamReader(cshtml.FullName))
                {

                        // Let Razor do it's thang...
                        var compileUnit = razor.GenerateCode(re).GeneratedCode;

                        // Pull the code into a stringbuilder, and append to the main project:
                        StringBuilder sb = new StringBuilder();
                        using (StringWriter rw = new StringWriter(sb))
                        {
                            cs.GenerateCodeFromCompileUnit(compileUnit, rw, csOptions);
                        }

                        var content = sb.ToString();
                }
            }

c#

asp.net-mvc

roslyn

0 Answers

Your Answer

Accepted video resources