简体   繁体   English

如何使用RegisterStartupScript调用JavaScript警报框后停止VB代码执行

[英]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. 我有一个vb.net项目,正在使用javascript进行服务器端控件验证。

I am registering the javascript code to validate the controls using a asp button click event. 我正在注册JavaScript代码以使用asp按钮单击事件来验证控件。 The problems is that I want to stop code execution if validation fails (indicated with an alert). 问题是,如果验证失败(带有警报),我想停止代码执行。

My code is below: 我的代码如下:

VB: 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: 使用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. 这里的问题是Javascript是在客户端的浏览器中执行的,而不是在服务器上执行的。 This means that by the time the Javascript runs, the VB on the server is already completely finished executing. 这意味着在运行Javascript时,服务器上的VB已完全完成执行。

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 如果txtbAcronym控件是由ASP.net页在服务器端创建的(而不是由JS脚本动态创建的客户端),则可以

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. 如果不是,那么您需要找到其他方法来提前检测这种情况或在客户端上复制行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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