Usually I try to create a separate .js file for most / all of my javascript codes. Usually, I need the generic bahvior to be applied to many elements that are dynamically created using ASP controls or server-side code, so I cannot encode everything into a .js file.
I found that the main reason you want to generate javascript on the server is because you will not know the identifiers of the elements until the page is displayed. Therefore, I am trying to condense this dependency as much as possible so that I generate as little javascript as possible. For example, in traditional ASP.Net (not MVC), if I were to represent a set of forms, for example, in each example with several fields, then I would probably have something in this code:
protected void FormRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { Control form = e.Item.FindControl("MyForm"); ClientScript.RegisterStartupScript(this.GetType(), "prepareForm_" + form.ClientID, @"prepareForm('" + form.ClientID + "');", true); }
A separate .js file will include a definition of the prepareForm function, which will be something like this:
// define a formPresenter "class" that encapsulates the behavior for a given form function formPresenter(formId) { this.setFirstName = function(value) { $("#" + formId + "_FirstName").val(value); } this.setLastName = function(value) { $("#" + formId + "_LastName").val(value); } // create other functions to handle more complicated logic // clear fields this.clearInputs = function() { this.setFirstName(""); this.setLastName(""); //... } // receive Json object this.handleJson = function(json) { this.clearInputs(); // populate fields with json object this.setFirstName(json.FirstName); this.setLastName(json.LastName); //... } // "constructor" logic } function prepareForm(formId) { // create a new formPresenter object and shove it onto the specified element as the "presenter" document.getElementById(formId).presenter = new formPresenter(formId); }
Now almost all of your actual logic is in its own .js file, which should be much easier to maintain. If you need to access the formPresenter object for this form, you just need to get a link to any element referenced by the formId parameter and access the host variable:
"document.getElementById(" + form.ClientID + ").presenter.handleJson(json);"
Note. Since I use jQuery, I found it less necessary to even include any javascript generated by the server. Usually I can find the elements I need by looking for a specific CSS class name (or something like that) and do whatever installation / initialization I need.