0

There seriously has to be a better way to do this than what I'm finding on the net.

<script type="text/javascript">
    function Sub()
        {
            if (document.getElementById("DatePicker1").Text == "")
                alert("Select a date");
            else
                Submit(); //this is the c# function
        }
</script>

<asp:Button ID="Button1" runat="server" OnClientClick="Sub()" PostBackUrl="~/Default.aspx" Text="Submit" />

Why is it that if I changed it to OnClick = "Submit" I could do that, but trying to do it after clientside validation its so hard! Very frustrating. I'm a pretty experienced programmer, but new to web related stuff so this while client vs server nonsense keeps getting in the way.
Please let me know of any good solutions. I'd rather not use jQuery as I want to study that separately later. Thank you.

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Timotheus
  • 201
  • 2
  • 11
  • If you are writing a web based (and thus browser based) web application then you are going to have to deal with front end ui -- which means javascript. I think you should bite the bullet and learn it. An experienced programer should have no problem using jquery or native javascript to do some validation. – Hogan Dec 13 '13 at 15:37
  • 2
    Wow, you are really grumpy here, probably will get less results on SO if you keep it up... I know I'm moving on. – Hogan Dec 13 '13 at 15:38
  • Yep, just that fact that you would consider using that vulgar word or a substitute is totally inappropriate here. Remember, everyone on SO who is helping you is doing so 100% out of kindness -- you're not paying them, they don't work for you, etc. Treating them with anything but 100% respect comes across... well I'll let you fill in with one of the words you tend to use. – Hogan Dec 13 '13 at 16:12

2 Answers2

3

You actually don't need to call a web method from your Javascript. You can try the following:

Have OnClick and OnClientClick with your button. In OnClientClick do return Sub()

<asp:Button ID="Button1" runat="server" OnClientClick="return Sub()" 
      OnClick="Button1_Click"  PostBackUrl="~/Default.aspx" Text="Submit" />

In Button1_Click event you can call your method Submit

In your Javascript, return true or false based on the validation.

<script type="text/javascript">
    function Sub()
    {
        if (document.getElementById("DatePicker1").Text == "")
        {
            alert("Select a date");
            return false;
        }
        else
        {
            return true;
        }
    }
</script>

This will prevent the OnClick event from getting fired in case of failed validation.

Habib
  • 219,104
  • 29
  • 407
  • 436
1

OnClick will work on server side , OnClientClick will execute on client side before control passed to server.

If the client side code returns TRUE then it will go to server. If it is used to validate and return false, it will not go to the server.

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69