Using JavaScript with ASP.NET

Why Use JavaScript?

There are a few technologies that you must be comfortable with if you want to do any serious web development. HTML for content, CSS for formatting and JavaScript for dynamic programming are recognized as the three foundation skills that any good web designer needs.

ASP.NET programmers might be tempted to do away with the last item given that .NET code can do virtually anything when combined with HTML and CSS but JavaScript is still very important and the reason lies in the different domains in which each language operates.

ASP.NET is a server language. It requires an installation and special configuration of IIS to even properly render the web pages generated by it.  A simple button click generates a series of events that involve a trip back to the server and a refresh of the page before the code in the button’s click event is even executed.  This costs time,  bandwidth and extra care on the part of the developer to ensure that any session data involved is properly handled during the postback.

JavaScript is a client-side language that is interpreted by the browser on the user’s machine.  All you need to write a page with JavaScript is a copy of Chrome and a free editor like Notepad++ or Visual Studio Code.  Chrome even provides developer tools that will allow you to step through your JavaScript code to find errors.  The content of web pages can be changed immediately without a refresh.  Games and applications can be designed and deployed just with HTML, CSS and JavaScript.

Knowing this, maybe the question becomes ‘Why use ASP.NET??’ and the answer is that each language has its proper role.  For all its power, JavaScript is not practical for accessing server resources like databases because of security concerns.  You also don’t want a web page downloading code to a user’s machine and then executing that code to change user files so it’s prevented from affecting them.  It’s also possible to quickly do a large amount of work on a web server and then deliver the end result to the user’s browser as needed without depending on whatever resources or configuration a user has locally.

When you add a server language like ASP.NET or PHP to the HTML / CSS / JS triad, you have a very powerful system for designing online applications and a great deal of control over how and when those applications collect, process and communicate data to the user.  Also, once you know either C# or JavaScript, the other is easier to learn because the syntax is so similar.

You can continue with the article below or watch the companion video and demonstration for this article here:

Implementing JavaScript

One of the first uses of JavaScript in an ASP.NET site might be for user input validation.  If you can catch passwords that don’t meet the policy restrictions (8 characters, mix of letters and numbers, etc.) as soon as the user clicks the button, you can save a trip to the server. If the password does meet requirements, then ASP.NET can take over and validate it against the user’s password in the database.

For an example, look at the screenhot of a very simplified login create form below.

The fields and Create button shown are ASP.NET controls as opposed to HTML controls. These controls can trigger methods and expose properties to C# code on the server.  HTML input and button controls run locally within the browser.

Here’s the markup for the button shown above.

<asp:Button ID="btnNewLogin" OnClientClick="return validateNewUserInfo();" 
runat="server" OnClick="btnNewLogin_Click" Text="Create Account" 
style="height: 26px" />

Now let’s compare it to the HTML you would see for a normal HTML button.

<input id="Button1" type="button" OnClick="validateNewUserInfo();"value="button" />

Notice a couple things about the two code samples:

  • The ASP.NET control includes the instruction runat=”server” which instructs ASP.NET to access the server code.
  • Both buttons are referencing a JavaScript function called validateNewUserInfo() at the bottom of the page which gets the values from the text fields and then tests them against various rules.  Here’s an abbreviated version:
<script>
 function validateNewUserInfo() {

let validated = true;
 let userName = document.getElementById('<%= newUser.ClientID %>').value;
 let userPass = document.getElementById('<%= newPass.ClientID %>').value;

if (userName != undefined) {
 if (userName.length < 8) {
 validated = false;

...

return validated

}

</script>

OnClientClick

The first catch that comes with using JavaScript with ASP.NET is that both languages have an OnClick event for buttons and ASP’s event takes precedence. That’s why, in the ASP.NET markup above, it uses the OnClientClick event to reference the JS function.  This event needs to return either a True or False value. If it returns a False value, it will prevent the ASP OnClick() from firing.  This means that if the user input is not valid, the JavaScript should return False in order to prevent ASP.NET from calling the server method at all.  Otherwise it returns True and everything goes as normal.

The OnClientClick event also uses the word ‘return’ as shown here:

OnClientClick="return validateNewUserInfo();"

This is necessary to get ASP.NET to respond correctly to a False value.

ClientID

Another thing you need to know is seen in this line from the JavaScript function:

document.getElementById('<%= newUser.ClientID %>').value

The getElementById function in JS is used to get and change values in controls such as text boxes.  In the markup shown earlier, you’ll see that both the HTML and ASP.NET buttons have IDs that can be referenced in this way.  The catch is that when ASP.NET renders its controls to an HTML page the browser can read, it doesn’t always pass on the names shown in the Visual Studio development environment.   Here’s the HTML markup that resulted from the User Name textbox in ASP.NET.

<input name="ctl00$ContentPlaceHolder1$newUser" type="text" id="ContentPlaceHolder1_newUser" />

The ASP.NET Textbox is rendered as an HTML input box but the ID is changed to “ContentPlaceHolder1_newUser” becase in Visual Studio, the page is using a master page to provide a template and the textbox is actually located within the ContentPlaceHolder1 template section.  This means that the ID value HTML receives is based on that relationship.

It would be a pretty big hassle to write JavaScript while having to remember what ID ASP.NET might assign to a control and that’s where the ClientID property comes in.

document.getElementById('<%= newUser.ClientID %>').value

The ‘<%= … %>’ tags provide a way to look at the actual ASP.NET control and get whatever ClientID will be assigned. Because the control is still be rendered in HTML, we use the ‘value’ property to get the actual value.

By learning JavaScript and understanding how to use OnClientClick and ClientID, you can write some pretty sophisticated validation into your ASP.NET pages without touching the server.

Other ASP.NET properties

As mentioned above, it’s important to remember that JavaScript is referring to HTML controls even if they originated in ASP.NET.  In .NET, you might want to set the Visible property of a label or other control to False to hide it from the user in certain cases but this will actually prevent it from being rendered to the HTML page and JavaScript won’t be able to work with it.  If you will be using JS to reference fields, be sure to anticipate what properties will actually be available.  In the case of the invisible label, it might be better to create a label control with no text and then set the HTML InnerText value to the text that it needs when appropriate.

Get to Know HTML Controls

HTML5 has introduced a number of new input controls that might serve your needs just as well as ASP.NET controls and you can still use them on your .NET pages.  The new controls include a color selector and specialized telephone, e-mail and date/time inputs. When selecting controls, it’s good to ask yourself if you really need the control to run on the server or if it will work just fine from the local browser.  These controls can also be placed inside an ASP.NET master page without being renamed so your JavaScript will know exactly what ID to reference. Ultimately, it’s a good idea to be familiar with both sets of controls and use the technology that works best in each situation.