ASP.net RequiredFieldValidator not preventing postback

后端 未结 5 1089
猫巷女王i
猫巷女王i 2020-12-08 10:11

I have a question about what could stop a RequiredFieldValidator from preventing a postback.

I began working on an older, but simple aspx form and my predecessor use

5条回答
  •  一整个雨季
    2020-12-08 11:04

    I had the same problem, but the answer turned out to be quite different. I was also upgrading to .NET validation from server-side hard coded validation.

    The issue in my case turned out to be related to the ASP.NET rewriting engine used from the MSDN article URL Rewriting in ASP.NET. Using the default implementation of the "Actionless Form" was the culprit - apparently this one was written based off of an earlier version of .NET and the JavaScript on the form that prevented the postback was not being send to the output because it was missing code.

    Anyway, in case anyone else is using this rewriting engine, the solution was to change the default implementation of ActionlessForm to the following:

    Public Class Form
        Inherits System.Web.UI.HtmlControls.HtmlForm
    
        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            MyBase.Render(New ActionlessFormHtmlTextWriter(writer))
        End Sub
    
    End Class
    
    Public Class ActionlessFormHtmlTextWriter
        Inherits HtmlTextWriter
    
        Sub New(ByVal writer As HtmlTextWriter)
            MyBase.New(writer)
            Me.InnerWriter = writer.InnerWriter
        End Sub
    
        Sub New(ByVal writer As System.IO.TextWriter)
            MyBase.New(writer)
            MyBase.InnerWriter = writer
        End Sub
    
        Public Overrides Sub WriteAttribute(ByVal name As String, ByVal value As String, ByVal fEncode As Boolean)
    
            Dim Context As HttpContext = HttpContext.Current
    
            'Skip the action attribute of the form control.
            If Not (name = "action") OrElse Not Context.Items("ActionAlreadyWritten") Is Nothing Then
    
                MyBase.WriteAttribute(name, value, fEncode)
    
            Else
                Context.Items("ActionAlreadyWritten") = True
            End If
        End Sub
    
    End Class
    

    What this does is simply supress the action attribute, but allow any other logic in the framework to run. This should future proof this in case Microsoft decides to change the form again.

提交回复
热议问题