View that is defined by the. cshtml or. vbhtml file can be executed and must first be compiled into a type that exists in an assembly, ASP.net MVC compiles the view file dynamically. When we deploy to asp.net mvc, we need to package the. cshtml or. vbhtml files. The first access to a view triggers the compilation for it, and a view corresponds to a type. We can modify the. cshtml or. vbhtml, and the first access after the view file is modified will result in a second compilation of the view. As with ASP.net traditional compilation, the view compilation defaults to directory based, meaning that multiple view files under the same directory are compiled into the same assembly.
In order to give readers a deep understanding of the compiler mechanism of the view file by ASP.net mvc, we use a simple example to determine what type the view file is ultimately compiled into, and which assembly is in. We have defined an extension method listviewassemblies for HtmlHelper in an asp.net MVC application, which is used to get the assembly that contains the view type that is currently loaded (the assembly name is prefixed with "app_web_").
1:public Static Class Htmlhelperextensions
2: {
3: Public static mvchtmlstring listviewassemblies (this htmlhelper helper)
4: {
5: Tagbuilder ul = new Tagbuilder ("ul");
6: foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies (). Where (A=>a.fullname.startswith ("App_Web_"))
7: {
8: Tagbuilder li = new Tagbuilder ("Li");
9: Li. InnerHtml = assembly. FullName;
Ten: ul. innerhtml+= Li. ToString ();
One: }
A: Return to new Mvchtmlstring (ul. ToString ());
: }
14:}
We then defined the following two controller types (Foocontroller and Barcontroller), each of which defined two action methods Action1 and Action2.
1:public class Foocontroller:controller
2: {
3: Public actionresult Action1 ()
4: {
5: Return View ();
6: }
7: Public actionresult Action2 ()
8: {
9: Return View ();
: }
11:}
12:
13:public class Barcontroller:controller
14: {
: Public ActionResult Action1 ()
: {
: Return View ();
: }
: Public ActionResult Action2 ()
: {
: Return View ();
: }
23:}
Next we create the corresponding view for the four action defined in Foocontroller and Barcontroller (the corresponding file path is: "~/views/foo/action1.cshtml", "~/views/foo/ Action2.cshtml "," ~/views/bar/action1.cshtml "and" ~/views/bar/action2.cshtml "). They have the same definition, where we display our own type and the currently loaded view-based assembly in view.
1: <div> Current View type: @this. GetType (). Assemblyqualifiedname</div>
2: <div> View assembly currently loaded:</div>
3: @Html. Listviewassemblies ()
Now run our program and in the browser by entering the appropriate address "sequentially" ("Foo/action1", "Foo/action2", "Bar/action1" and "Bar/action2") The access definition is defined in the four action of Foocontroller and Barcontroller, and four accesses the output results shown in the following figure.