简体   繁体   中英

How to stop vb code execution after calling javascript alert box using RegisterStartupScript

I have a vb.net project where I'm using javascript for server-side control validation.

I am registering the javascript code to validate the controls using a asp button click event. The problems is that I want to stop code execution if validation fails (indicated with an alert).

My code is below:

VB:

Protected Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles cmdSubmit.Click
    Dim sscript As New StringBuilder
    If (Not ClientScript.IsStartupScriptRegistered("committeeEditorValidator")) Then
        Page.ClientScript.RegisterStartupScript(Me.GetType(), "committeeEditorValidator", "committeeEditorValidator();", True)
    End If
        'Need the Sub routine to stop here if a Javascript alert is thrown.
         updateMemberInfo() 
    End Sub

Javascript:

if (document.committeeEditor.txtbAcronym.value.length < 1)
    {
        document.getElementById("hderror").value = "1"
        alert("You must provide a Committee Acronym!");
        document.committeeEditor.txtbAcronym.focus();
        return false;
    }
    document.committeeEditor.submit();
}

The problem here is that Javascript is executed in the browser on the client-side, not on the server. This means that by the time the Javascript runs, the VB on the server is already completely finished executing.

Your best option is to find a way to check the value while the page is being rendered. If the txtbAcronym control is created server-side by your ASP.net page (rather than dynamically created client-side by a JS script) then you can just do

If txtbAcronym.Text.Length < 1 Then
    Exit Sub
End If
updateMemberInfo() 

If not, then you need to find some other way to detect this condition ahead of time or replicate the behavior on the client-side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM