Monday, January 17, 2011

asp.net strongly typed view and virtual path provider

Use Case

Have custom system inspired by VirtualPathProvider samples from MSDN. Need ability to use strongly typed views.

Solution

In the case of using generic views (not-strongly types), everything works fine. The problem appears when I'm trying to use strongly-typed view as shown below:


<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Abc.Xyz.MyClass>" %>

The problem is obvious and well-known, if Views/ folder miss web.config file, asp.net mvc application can't load the view. In Virtual Path Provider solution is more tricky. The quickest solution (for me) was to add content of web.config file that must reside in views folder directly to main web.config file in separate location.

For example, if you have your VPP accepting smth like "~/page/xxx", the problem is easily solved by adding following snippet to your web.config

+++++


  <!-- Important change for virtual pages -->
  <location path="page">
    <system.web>
      <httpHandlers>
        <add path="*" verb="*"
            type="System.Web.HttpNotFoundHandler"/>
      </httpHandlers>

      <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
      <pages
          validateRequest="false"
          pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
          pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
          userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <controls>
          <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
        </controls>
      </pages>
    </system.web>

    <system.webServer>
      <validation validateIntegratedModeConfiguration="false"/>
      <handlers>
        <remove name="BlockViewHandler"/>
        <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
      </handlers>
    </system.webServer>
  </location>

++++

During research, I've found several good articles:




No comments:

Post a Comment