Posting a C# form from JavaScript

Posted on 2005-03-17
Medium Priority
Last Modified: 2011-09-20
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?

Question by:Pete2003
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3

Expert Comment

ID: 13568814
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!

Author Comment

ID: 13569724
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 ?

LVL 23

Expert Comment

ID: 13582033
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.

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


Author Comment

ID: 13582336
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 ?
LVL 23

Accepted Solution

b1xml2 earned 2000 total points
ID: 13582500
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, "");

// -->
LVL 23

Expert Comment

ID: 13582520
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.

Author Comment

ID: 13582654
I have NEVER used validators .. will look at them .. txs a lot ... worth a few more points :)

LVL 23

Expert Comment

ID: 13582669
Thanks Pete =)

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question