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?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

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, "");

// -->

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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 =)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.