Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 333
  • Last Modified:

Posting a C# form from JavaScript

Hi All,

I have a HTML button sitting on my page <INPUT>.
This button calls some JS code do do client-side validation.

I now want the JS code to call my function inside the C# code...

In the JS code I have:

This calls the C# code, but only the main Page_Load function.

I want to load a specific function.

I know I could populate a hidden field on the HTML page to tell me which function to call ...
Is there a neater way to call a C# function?

  • 4
  • 3
1 Solution
C# functions are available in the Server and your Javascript code is sent to the browser for client side validations and other actions. So the only way to call C# function you have written in the code behind is by posting the page back.

1. In your javascript, after all the validations are performed, do document.window.submit(); - This will do a postback.

2. In the page load find out the postback is caused by your explicit calling..this can be done by many ways..either by passing in hidden value or in args collection etc.,

3. Call your C# function from Page_Load

I can send you sample code if you would like!
Pete2003Author Commented:
I have a little proble with #2

how do I pass things back ...

as I said above I was using the Form["???'] to get data

you said I can pass an args collection ... could you show me how ?

If I may, why do you want to determine from client-side Javascript what C# function is called. This generally is not the norm plus it opens up with potential abuse. From what you have stated here, your client-side scripts do client-side validation. If as I suspect, you want to also validate them server-side when the postback occurs, then you can use CustomValidator controls and you do not need client-side code determining which server-side code executes.
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Pete2003Author Commented:
ok ...

Simple example ... enter new password dialog with just two edit boxes for the password and password retype ...

on client side:
1) check that password len > 0
2) check that pass1 = pass2

then go to server:
3) write new password to database

now on that window I have 2 asp:editbox and an <input> button ...
so when I press the button I execute some java script but I also need a way to get to the C# code to actually write the password to the database.

Is there a better way to do this ?
yes, there is a better and "proper" way. The thing though here is not to concentrate too much on the solution that I am about to pro-offer. You should pay attention to the parts that relate to the .NET Framework.

<%@ Page Language="vb"%>
<script language="vb" runat="server">
Sub ComparePassword(ByVal Source As Object, ByVal Args As ServerValidateEventArgs)
'Only Validate When No Other Validation Failure Occurs
Dim Value As Boolean = True
If rfvPassword.IsValid AndAlso rfvConfirmPassword.IsValid Then
 Value = txtPassword.Text.Trim().Equals(txtConfirmPassword.Text.Trim())
End If
Args.IsValid = Value
End Sub

Sub Save(ByVal Sender As Object,ByVal Args As EventArgs)
If Page.IsValid Then
'Only When The Validation Rules Are All Passed
'Then Connect To The DataBase And Make The Change Here
Response.Write("Hello World")
End If
End Sub
<title>Password Change</title>
.error {cursor:hand;font-weight:bold;color:red;}
<form runat="server">
<table cellpadding="0" cellspacing="0" border="0">
      <td><asp:TextBox ID="txtPassword" Runat="server" TextMode="Password" />
      <asp:RequiredFieldValidator ID="rfvPassword" Runat="server" ControlToValidate="txtPassword" Display="Dynamic"><span title="Password Required" class="error">***</span></asp:RequiredFieldValidator>
      <td>Confirm Password</td>
      <td><asp:TextBox ID="txtConfirmPassword" Runat="server" TextMode="Password" />
      <asp:RequiredFieldValidator ID="rfvConfirmPassword" Runat="server" ControlToValidate="txtConfirmPassword" Display="Dynamic"><span title="Confirm Password Required" class="error">***</span></asp:RequiredFieldValidator>
      <asp:CustomValidator ID="cvPasswordCompare" Runat="server" ClientValidationFunction="ComparePassword" OnServerValidate="ComparePassword" Display="Dynamic"><span title="Confirm Password Does Not Match Password" class="error">***</span></asp:CustomValidator>
      <td><asp:Button ID="btnSubmit" Runat="server" OnClick="Save" Text="Submit" /></td>
<script language="javascript">
function ComparePassword(source,args)
  var pwd = Trim(document.forms[0]["txtPassword"].value);
  var comp_pwd = Trim(document.forms[0]["txtConfirmPassword"].value);
  args.IsValid = pwd.length == 0 || comp_pwd.length == 0 || pwd == comp_pwd;


function Trim(value)
      return value.replace(/(^\s*)|(\s*$)/g, "");

// -->
The use of validators is something that you should look into.
Also the robustness of validation in the .NET Framework and ASP.NET.

If the user disables javascript within his browser, all the validation still takes places server-side just as they would do client-side if javascript was enabled. This allows for consistency of validation being applied both client-side as well as server-side. The client-side customvalidator function just simply does the same thing as the server-side method. It simply prevents an unnecessary postback. The beauty of validator controls is that you reduce the amount of code maintenance and synchronisation between client and server code.
Pete2003Author Commented:
I have NEVER used validators .. will look at them .. txs a lot ... worth a few more points :)

Thanks Pete =)

Featured Post


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now