Reputation: 1
In a web application I am using a button_Click method in VB.Net to occur when a button is clicked.
I have the following line at the top of my VB.NET method:
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "myFunction", "myFunction();", True)
I want that script to finish before my VB.NET script carries on. Basically, I have validation in my javascript that I want to complete before the VB.NET takes the "validated" data and inserts it into a database.
Upvotes: 0
Views: 551
Reputation: 19466
This is assuming that myFunction
is a javascript function existing on your client side. It will call myFunction
on the client side.
<asp:Button ID="btntest" runat="server" Text="Add Record"/>
<asp:CustomValidator ID="myCustomValidator" runat="server" ControlToValidate="someControl" ErrorMessage="Validation Error" ClientValidationFunction="myFunction"></asp:CustomValidator>
This is assuming that you javascript is doing some validation as well. It would look something like this. If args.IsValid = false
, then the validator won't allow a postback and the vb.net code won't execute. This is the point of a validator.
function myFunction(sender, args) {
var someControl = document.getElementById(sender.controltovalidate).control;
//Let's assume someControl is a textbox and we don't want it bigger than 10
if (someControl.value > 10) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Hopefully, this gets you going. Let me know if something isn't working right and you need more help.
Upvotes: 0
Reputation: 416121
This betrays a misunderstanding of how web forms work. Here's what really happens:
I need to point out some things about this process, namely that order between steps 3 and 4, steps 6 and 7, and steps 11 and 12 are accurate. When there is working page visible in the browser, the server has already moved on and destroyed anything used to create that page (except Session variables). While VB.Net code is running, the browser doesn't even have a page to show yet.
What you should learn from this is that at time the javascript runs, not only has the VB.Net method already finished, but the entire page class was already destroyed. There's an idea of continuity here for both the browser's web page and the VB.Net Page class instance that just doesn't happen. It's just nice that all this happens in a way that is mainly transparent to the user.
Fortunately, there are some things you can do to avoid this full process. You might look into using an UpdatePanel for part of your page, changing the button to trigger a WebMethod, or translating more of the VB.Net code into javascript in the first place. However, all of these will likely require significant re-thinking of how your page is going to work. In this case, you might find and a Validation control best fits your needs.
Upvotes: 1