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

时间:2015-07-08 15:37:28

标签: javascript asp.net vb.net code-behind

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();
}

1 个答案:

答案 0 :(得分:1)

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.