ASP.NET MVC 3: Generate unobtrusive validation when BeginForm is on the layout

前端 未结 5 1629
一个人的身影
一个人的身影 2020-12-09 13:31

I just realized that when I place a form tag on my layout page, surrounding the RenderBody section, the unobtrusive validation is not being generated. Something like this:

5条回答
  •  盖世英雄少女心
    2020-12-09 13:46

    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 class, the default base class for views and do the FormContext swap there.

    abstract public class FormFixWebViewPage : FormFixWebViewPage
    {
    }
    
    abstract public class FormFixWebViewPage : WebViewPage
    {
        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:

    
        
        
        
            
                
                
                
                
                
            
        
    
    

    提交回复
    热议问题