开发者

Call C# Function From JavaScript/JQuery In Asp.net webforms

开发者 https://www.devze.com 2023-04-05 13:31 出处:网络
So, i have an aspx page which looks like this: <%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" %>

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?


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";
}


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?


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


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());
}


<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
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消