1

iv'e got an asp button which performs another task besides postback

i have done this by adding javascript code to the button as follows

       if( !IsPostBack )
            btn1.Attributes.Add("onclick", "f();");

i'm not sure of 2 things

the first :

where in the cs code i should add the function f() , currently i'm doing it in page load while ignoring postbacks because then the function would have already been added(i might be wrong)

the second :

is there any to make the function execute only if the page was validated ? (after postback)

thanks in advance eran.

2

3 Answers 3

2

I would use OnClientClick instead of adding the click event throug the attributes. As for your JavaScript, I would add it in the ASPX part. Depending on what the function does, you might be able to avoid the code behind all together and do something like this:

<asp:Button ID="Button1" runat="server" Text="Hi" OnClientClick="javascript:return f();" OnClick="Button1_Click" />

From your f() function, kick off the validation, and return true if validation passes, otherwise return false. If OnClientClick returns true the page will post back, and if it returns false the page will not post back.

Sign up to request clarification or add additional context in comments.

3 Comments

and don't use javascript:func - it's so 90's! The function name is sufficient.
thanks ,that was the right way to go. btw , could i have used my validators through the java script ? what i did is create my own validation in order to decide if to proceed or not , what i mean is if lets say i got a required field validator could i do something like RFValidator1.Validate() ?
Yes, you can probably do your validation from within your JS function. Just call Page_ClientValidate()
1

1st Question

You will need to add it each time.

btn1.Attributes.Add("onclick", "f();");

2nd Question

You can check the validity of a page by checking the Page.IsValid Property

Comments

0

Unobtrusive JavaScript

If you're serious about javascript then you don't want to write inline javascript. You will want to create an event handler in javascript code inside the script tags or in a external file.

If you're using .NET 4 server control id:s will be good, else I would use jquery's contains selector. Search for the given server control ID.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.