LA.NET [EN]

Sep 19

The MVC platform – the WebFormView class

Posted in ASP.NET MVC      Comments Off on The MVC platform – the WebFormView class

So, after a long walk we’ve finally reached the WebFormView class. This class is responsible for instantiating a view (which may be an ASP.NET page or a user control) and generating the output that is going to be sent to the client. The class implements the IView interface which was reintroduced in this last preview (5, if you’re reading this in the future) and looks like this:

public interface IView {
        void Render(ViewContext viewContext, TextWriter writer);
}

As you can see, the Render method receives a ViewContext which contains information about the current context and a TextWriter instance you can use to output the HTML of the pages. It’s important to understand that the WebFormView isn’t an ASP.NET page or ASP.NET user control; it’s just a class that will instantiate the requested page or user control and render its HTML.

In order to achieve this, the WebFormView class’ constructors will receive the path to the requested resource and (optionally) the path to a master page that must be applied to the view that is being built (master pages will only be used when rendering a view). There’s also another interesting property exposed by the class: the BuildManager property.  This property lets you specify the builder (an IBuildManager type) used for getting an instance of the class from the specified path. The IBuildManager interface defines the following contract:

internal interface IBuildManager {
  object CreateInstanceFromVirtualPath(string virtualPath, Type requiredBaseType);
  ICollection GetReferencedAssemblies();
}

The BuildManagerWrapper builder is used by default and it implements the previous interface by reusing the BuildManager class.

The WebFormView class will call the IBuildManager.CreateInstanceFromVirtualPath on the current builder in order to create a view instance. But here’s the thing: it will always try to convert the created instance into an element of type ViewPage or ViewUserControl. These are the basic types that your ASP.NET MVC pages or user controls must extend in order to be considered MVC views. As you might expect, these classes extend the traditional Page and UserControl ASP.NET classes. We’ll come back to these classes in a future post. For now, knowing that both of them expose a ViewData property and a RenderView method is more than enough for the rest of this post.

Back to the WebFormView class…so, after instantianting the object and casting it to ViewPage or ViewUserControl, the WebFormView class ends up passing the ViewDataDictionary (which contains info about the current view) and calling the RenderView method in order to generate the HTML sent back to the client.

And that’s all. There’s really nothing more to it. On the next post, we’ll take a closer look at the ViewPage and ViewUserControl classes. Keep tuned!