4

So, i have an aspx page which looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

I would like to know, how I can write JavaScript (e.g. jQuery) code that will call a function from my C# Code. Lets say this is my C# method:

protected void XXX(object sender, EventArgs e)
{
    Response.Redirect("pagewho?");
}

Thanks again, Alon. :)

EDIT:

This is the full code i am using the moment:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
  <script type="text/javascript">
      validateStuff = function () {
          var isValid = true;
          var txt = document.getElementById("TextBox1");

          if (txt) {
              if (txt.value.toLower() != "james") {
                  isValid = false;
              }
          }
          //perform validation and return true/false
          return isValid;
      }

  </script>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" OnClientClick="return validateStuff();" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:TextBox ID="TextBox1" runat="server" Height="25px" Width="135px"></asp:TextBox>
        <br />
        <br />
        <br />
    </div>
    </form>
</body>
</html>

but, no matter what i am wireting in the textbox, its return true. any help?

Alon M
  • 1,583
  • 7
  • 30
  • 44

5 Answers5

7

You can use __doPostBack from the script, and use the RaisePostBackEvent method in the code behind to perform your server-side logic. If you're looking to do a redirect, this would probably be the best way.

EDIT

If you're looking to do some validation in JavaScript when a button is clicked, use OnClientClick to perform your JavaScript validation, and return true if the validation succeeds.

<asp:Button ID="Button1" runat="server" OnClientClick="return validateStuff();" OnClick="Button1_Click" />

Your JavaScript validation:

validateStuff = function(){
    var isValid = true;
    var txt = document.getElementById("<%=TextBox1.ClientID%>");
    if (txt.value.toLower() != "james"){
       isValid = false;
    }        
    return isValid;
}

If the validateStuff function returns true, a postback will occur and you can handle your save/update logic in the button click event:

protected void Button1_Click(object sender, EventArgs e)
{
    //save some stuff to the database

    string txtValue = TextBox1.Text.Trim();
}

In JavaScript:

redirectToAnotherPage = function(){
    __doPostBack("<%=SomeServerControl.ClientID%>", "someArgument");
}

In the code-behind:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    //call the RaisePostBack event 
    base.RaisePostBackEvent(source, eventArgument);

    Response.Redirect("anotherpage.aspx");
}

If all you're looking to do is bring the user to another page, you can also do this:

redirectToAnotherPage = function(){
    window.location.href = "somepage.aspx";
}
James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • a side note - `__doPostBack` is not a JS function. It is generated automatically when you add a LinkButton to the form. What actually `__doPostBack` does is - puts some data to hidden fields and submits the form. so in general your post doesn't answer OP's question. – Nika G. Sep 16 '11 at 12:32
  • You are incorrect. Most all ASP.NET controls (except for Buttons and ImageButtons) use `__doPostBack` to perform postbacks, and it is both an accepted and reliable technique. If you look at OPs question, it appears that they are looking to trigger a `Response.Redirect` from the client-side, and `__doPostBack` is a perfectly acceptable way to achieve that. – James Johnson Sep 16 '11 at 12:40
  • OP is not trying to `Response.Redirect`, I guess so... and `__doPostBack` unlike to `Submit()` is not a built in JS function. As I said `__doPostBack` uses `Submit()` after writing some data to hidden fields – Nika G. Sep 16 '11 at 13:03
  • It depends on what you need to validate. Is it just simple validation? Can you revise your question to include details of what you need to validate? You can use jQuery to execute an AJAX call to another page, which you can use to perform business logic validation and return validation status. Another alternative is to do your validation server-side, which will require a full postback or an asynchronous callback using AJAX. – James Johnson Sep 16 '11 at 13:50
  • So. it is working. but, how about if i need to get a textbox info to my C# function. will the java sciprt able to check it? i didnt do it in my life before. can you give me hand mate? – Alon M Sep 16 '11 at 13:52
  • If the JavaScript validation function returns true, the form will postback and you'll have access to the TextBox value in the server-side button click event. – James Johnson Sep 16 '11 at 13:57
  • But.. you dont understand my qustion. i want the java script will check if something is woritedd in the textboes.. like if textboxa = "James" and textbox2 = "Johnson". if it does, i will return true, it not, i will rutrun false. – Alon M Sep 16 '11 at 14:01
  • See edited answer. I've included an example of how to validate a TextBox in the JavaScript function. – James Johnson Sep 16 '11 at 14:05
  • @Alon M: Follow my example. I created an `isValid` boolean variable, which is used throughout the validation process and returned at the end of the function. – James Johnson Sep 16 '11 at 14:39
  • I copyed your function, and my html is :


    , when i cliked on my button, no matter what text is in the textbox1, its reutrn true
    – Alon M Sep 16 '11 at 14:41
  • What do you have in your `validateStuff()` function? That's the most important part. – James Johnson Sep 16 '11 at 14:46
  • – Alon M Sep 16 '11 at 14:58
  • It looks like it's not finding the TextBox. After the `document.getElementById` line, put an alert: `alert(txt);` if it shows as undefined, then there's your problem. – James Johnson Sep 16 '11 at 15:01
  • Its says, Objet HtmlInput Element – Alon M Sep 16 '11 at 15:13
  • Please edit your question and include the code that you're currently using. – James Johnson Sep 16 '11 at 15:15
  • When referencing the `TextBox` in the JavaScript function, you need to use the ClientID: `document.getElementById("<%=TextBox1.ClientID%>");` – James Johnson Sep 16 '11 at 15:29
  • I also removed one of the `if` statements. Use the code in my edited answer. – James Johnson Sep 16 '11 at 15:31
  • Still nothing. no matter what is the text there. nothing happnd, and i used your new code and everything..., – Alon M Sep 16 '11 at 15:58
5

In order for client-side code to call server-side code, you probably need to use AJAX. Since you mention jQuery, it has a very handy function for making that call. But making the call from the JavaScript is only half the story, you'll also need something on the server listening for that call. If you're going to use jQuery (as opposed to other options, such as the AJAX Toolkit) then I recommend not having the method be "on the page" but rather be its own resource. I recommend using an HttpHandler for responding to the AJAX calls.

The key thing to remember here is how this is structurally different from simply posting back to the page. Using AJAX, these calls happen asynchronously within the page. So the first thing you should know is that Response.Redirect() won't work in this case. It will redirect the AJAX call, not the currently open page. There may be ways to use the post-back methodologies within ASP.NET to get around this, but I have to ask... if all you're doing is redirecting then why not just do it client-side? JavaScript is plenty capable for this. You can redirect from the server on a post-back easily enough, but from within JavaScript why not just have the JavaScript do it?

James Johnson
  • 45,496
  • 8
  • 73
  • 110
David
  • 208,112
  • 36
  • 198
  • 279
  • The Fuction was just ot expline what i am about to do, i want to call a fuction that will register peploe to the SQL, after the js will check thay wrote everytig fine.. if you have any way to show me how to do it simple.. i will like that, thanks.. – Alon M Sep 16 '11 at 12:31
  • It sounds like you need to perform some validation in JavaScript before submitting a form. Are you doing this on a Button click? If so, use `OnClientClick` to validate, and return true if validation succeeds. Returning true will cause a postback, and you can handle the server-side logic in the button click event. – James Johnson Sep 16 '11 at 13:10
  • @Alon M: Should the registration process happen asynchronously, or just the input validation? (Keep in mind that input should be validated in multiple places. Validate it on the page with JavaScript for a smooth user experience. Validate it on the website's back-end code for actual validation of the input, since anything client-side can be changed. And validate it in the data (the data access code, the database itself, etc.) for data integrity.) If the registration itself needs to happen asynchronously, then you're definitely looking at an AJAX call. Otherwise, simple JavaScript will do. – David Sep 16 '11 at 13:30
  • I just need a javasciprt code to see if the user did what he sould, puted username right, password, age etc..etc... when he dose. i need it to call a function my C# code, that will register him (she will also check the db and everything..) – Alon M Sep 16 '11 at 13:33
  • @Alon M: That's kind of a broad thing to ask for on Stack Overflow. What specifically needs to happen asynchronously? You can do the UI validation on the page. (There's a jQuery plugin that works pretty well for that: http://bassistance.de/jquery-plugins/jquery-plugin-validation/) But then your requirements start to get a little vague. Does the actual registration need to happen asynchronously? Or would that just happen when posting the page? (The latter is far more common.) We can't write the whole thing for you, but we can help you with specifics where you're stuck. – David Sep 16 '11 at 13:43
3

You can call C# method by making it webmethod. See this URL: http://www.xdevsoftware.com/blog/post/Call-WebMethod-from-Javascript-in-ASPNET.aspx in Javascript it is call pagemethod.

But for your example, i would suggest you just pre-populate value pagewho? using asp.net tags when HTML is rendered by asp .net.

Example (in javascript):

GoToLink("<%= YourCodeBehindMethodReturingURLToPutHere() %>");

Reference: http://weblogs.asp.net/ahmedmoosa/archive/2010/10/06/embedded-code-and-inline-server-tags.aspx

Yogee
  • 1,412
  • 14
  • 22
3

One way to call a C# method from client using JavaScript is using webmethods.

You need to define a public static method in your code behind and add to it the [WebMethod] attribute.

In this example I used a WebMethod that returns the current datetime as a string from the server:

[WebForm1.aspx.cs]

using System;
using System.Web.Services;

namespace TemplateWebMethod
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string MyMethod()
        {
            return DateTime.Now.ToString();
        }
    }
}

In the aspx page form you need to add an asp:ScriptManager with EnablePageMethods="true":

[WebForm1.aspx]

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TemplateWebMethod.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
      // during onload we set the onclick method of our button
      // to call MyMethod from the server
      window.onload = function(){
        document.getElementById('Button1').onclick = function() {
          PageMethods.MyMethod(myMethodCallBackSuccess, myMethodCallBackFailed);
        }
      }

      function myMethodCallBackSuccess(response) {
          // JavaScript code that will run
          // after MyMethod was run successfully on server
          // respose is the returned value of MyMethod
          alert(response);
      }

      function myMethodCallBackFailed(error) {
          alert(error.get_message());
      }
    </script>
</head>
<body>
    <form id="form1" runat="server">
      <asp:ScriptManager runat="server" EnablePageMethods="true" />
      <asp:Button runat="server" ID="Button1" ClientIDMode="Static" Text="Call MyMethod" UseSubmitBehavior="false" />
    </form>
</body>
</html>

For Button1:

ClientIDMode="Static" is used so Button1 will have same ID on client-side and we can search for it easily when adding client-side onclick.

UseSubmitBehavior="false" is required so that pressing the button will not cause a full postback.

In this example the WebMethod MyMethod will be called from codebehind by pressing Button1 so we set the onclick behavior for Button1 on window.onload:

window.onload = function(){
  document.getElementById('Button1').onclick = function() {
    PageMethods.MyMethod(myMethodCallBackSuccess, myMethodCallBackFailed);
  }
}

Where:

PageMethods.MyMethod(myMethodCallBackSuccess, myMethodCallBackFailed);

is the JavaScript method that calls the server side code.

We need to define its 2 callback methods for success and failure.

On success we popup a message with the returned value from MyMethod:

function myMethodCallBackSuccess(response) {
    alert(response);
}

On failed we popup a message with the error message:

function myMethodCallBackFailed(error) {
    alert(error.get_message());
}
Răzvan Flavius Panda
  • 21,730
  • 17
  • 111
  • 169
0
<head id="Head1" runat="server">
<script type="text/javascript">

    function checking() {
        var firstTwoChar = document.getElementById('TextBox1').value.substr(0, 2); //getting first two chars
        if (firstTwoChar == 'ok') { //if it starts with 'ok', submit the form to server
            document.forms['form1'].__OK.value = 1; // everything's OK, let the server know it, by writing 1 to hidden input field 
            document.forms['form1'].submit(); // submits to server
        }
        else {
            alert('thats not OK'); //form is not submited, alerting client about the error
        }
}

</script>
<title> </title>
</head>
<body>
<form id="form1" runat="server">
<input type="hidden" name="__OK" id="__EVENTARGUMENT" value="">
<input id="Button111" type="button" value="button" onclick="checking()" />
<asp:TextBox  ID="TextBox1" runat="server"></asp:TextBox>
</form>
</body>
</html>

as for codebehind

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        string ok = Request.Form["__OK"]; //getting data from hidden input
        if (ok == "1") // if it's 1 checking succeeded, thus it's ok to save data 
        insertTextBoxValueintoDBTable(TextBox1.Text); //saving data
    }
}
Nika G.
  • 2,374
  • 1
  • 17
  • 18