Search code examples
c#asp.netasp.net-mvcrazorviewengine

How is WebViewPage class transformed into html in ASP.Net MVC?


Until recently I thought that ASP.Net views are files (like .aspx or .cshtml) that can contain some .Net code inside themselves and are parsed with a view engine (like razor or aspx) into html files that are sent to a client's browser. Later I discovered that these views are actually converted into classes that derive from System.Web.Mvc.WebViewPage class. Apart from this I noticed some people referred to views as classes themselves. So my questions are

  1. If views are parsed into a class, how does this class then render an html document?
  2. Is it fair to say that views in ASP.NET are classes themselves or they are more like some kind of scripts on which bases a view engine forms an actual class?

Solution

  • A nice description of how the process works for Razor views can be found here.

    Basically the view file, in this case cshtml is first converted to a C# code file on the first request of that given page. The created class basically converts all the non-C# parts of the cshtml to C#. Mostly it is just writing out HTML literals as the response in the Execute method of the view.

    You can also see that the generated C# classes use #line directives to mark the lines of the original csproj file so that you can use the debugger to step through the original code and see where exceptions were thrown.

    So yes, views are basically classes (at least after they are first accessed they become classes) and the rendering is caused by writing the HTML literals inside the Execute method of the view to the response stream.