0

I wanted to know what is the best approach to program ASP.NET with JS? So far, I've been trying to code with the Codebehind attributes.add("onclick," ...."); is there a better more efficient way to use JS with ASP.NET?

thanks

11
  • 1
    i think writing your functions in a separate js file is much more efficient and flexible than trying to write all the your javascript functions from code behind. Commented Mar 27, 2011 at 13:26
  • But how can I achieve that? I dont know my control's IDs... (ctl100....) Commented Mar 27, 2011 at 13:27
  • Can you please be more specific? Do you write custom controls and need them to write some JS to the browser? Commented Mar 27, 2011 at 13:27
  • @oshafran - regarding the ID, you can find it by having this.ClientID in the control code behind.. Commented Mar 27, 2011 at 13:28
  • 1
    You could also use ClientIDMode="Static" if you're in .Net 4.0 Commented Mar 27, 2011 at 13:31

2 Answers 2

3

writing all your function in a separate js file is far more flexible that what you are doing now. The problem might be getting the control ID's in your js file. Well there are many methods.

Hardcoding

Just view the source and figure out the ID of the control which you want to use. this is easy but if you you may want to change the ID of the control at some point of time the respective functions will not work

Something like This

Declare a variable with all the the ClientIDs in the aspx file use it in the js file

var MyControlIDs = {"Textbox1":"<%= Textbox1.ClientID %>","Label1":"<%= Label1.ClentID %>"};

and in your js file var mycontrol= window.MyControlIDs and use it wherever you want

var textbox = document.getElementById(mycontrol.TextBox1);

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

Comments

0

Many WebControls have an OnClientClick property, which is equivalent of what you're doing. Also you can always set it in your markup for controls that don't have the property.

3 Comments

thanks. Is this is the best way to use JS & ASP.NET? using this programming method?
Also, what about other events? like onmousemove?
@oshafran I can't remember any controls that have an onmousemove property in .NET off the top of my head. Simplest would probably be to use the markup to set it. Otherwise the method you mentioned is the normal way. There are more convoluted ways, including creating your own controls or overriding the render.

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.