I've just run into the same problem, but possibly a better solution based on Darin Dimitrov's answer.
The trick is to create a page base type, based on the WebViewPage<T>
class, the default base class for views and do the FormContext
swap there.
abstract public class FormFixWebViewPage : FormFixWebViewPage<object>
{
}
abstract public class FormFixWebViewPage<T> : WebViewPage<T>
{
override public void Write(System.Web.WebPages.HelperResult result)
{
var originalFormContext = ViewContext.FormContext;
ViewContext.FormContext = new FormContext();
base.Write(result);
ViewContext.FormContext = originalFormContext;
}
}
And then in the Web.config
file under the ~/Views/
folder, alter the pageBaseType
attribute under pages
element, which can be found in the system.web.webPages.razor
section:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="<YOUR-NAMESPACE>.FormFixWebViewPage">
<!--pages pageBaseType="System.Web.Mvc.WebViewPage"-->
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<form>
tags in a page (as noted by @AidanBoyle), it could break the page functionality. Forms should not be nested according to the HTML standard. – Abney