This is the page that really got my goat. I'll list the relevant parts here for ease of reading.
Page.RegisterOnSubmitStatement Method
Allows a page to access the client OnSubmit event. The script should be a function call to client code registered elsewhere.
1: '[Visual Basic]2: Dim scriptString As String = "<script language=JavaScript> function doClick() {"3: scriptString += "document.write('<h4>' + myForm.myHiddenField.value+ '</h4>');}<"4: scriptString += "/" + "script>"5: RegisterHiddenField("myHiddenField", "Welcome to Microsoft .NET!")6:
7: RegisterOnSubmitStatement("submit", "document.write('<h4>Submit button clicked.</h4>')")8:
9: RegisterStartupScript("startup", scriptString)1: //[C#]2: void Page_Load(Object sender, EventArgs e)3: {
4: String scriptString = "<script language=JavaScript> function doClick() {";5: scriptString += "document.write('<h4>' + myForm.myHiddenField.value+ '</h4>');}<";6: scriptString += "/" + "script>";7: RegisterHiddenField("myHiddenField", "Welcome to Microsoft .NET!");8: RegisterOnSubmitStatement("submit", "document.write('<h4>Submit button clicked.</h4>')");9: RegisterStartupScript("startup", scriptString);10: }
Ok, how many things can you find wrong with this simple example?
- string concatenating to make a script block
- a bunch of totally unrelated code that muddies the point
- document.write() - who does that?
- VB and C# code don't even match; C# includes the method declaration; VB only includes the method body
- scriptString += "/" + "script>"
- definition says "The script should be a function call to client code registered elsewhere." but that is not what the example code does
Here's my stab:
1: //[C#]
2: void Page_Load(Object sender, EventArgs e)
3: {
4: if (!IsClientScriptBlockRegistered("doClickScriptKey"))
5: {
6: String scriptString = @"
7: <script type='text/javascript'>
8: function doClick() { alert('the form is about to submit!'); }
9: </script>";
10: RegisterClientScriptBlock("doClickScriptKey", scriptString); //"registered elsewhere"
11: }
12: RegisterOnSubmitStatement("submitScriptKey", "doClick();"); //"function call to client code registered elsewhere"
13: }