在Asp.net Webforms中从JavaScript/JQuery调用C#函数

4

所以,我有一个看起来像这样的aspx页面:

<%@ 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>

我希望了解如何编写JavaScript(例如jQuery)代码,以便从我的C#代码调用函数。假设这是我的C#方法:

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

再次感谢你,Alon。:)

编辑:

这是我目前正在使用的完整代码:

<%@ 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>

但是,无论我在文本框中写什么,它都返回true。可以帮忙吗?
5个回答

7
您可以在脚本中使用__doPostBack,并在代码后台中使用RaisePostBackEvent方法来执行您的服务器端逻辑。如果您想要进行重定向,这可能是最好的方法。
编辑: 如果您想在单击按钮时在JavaScript中进行一些验证,请使用 OnClientClick 执行JavaScript验证,并在验证成功时返回true。
<asp:Button ID="Button1" runat="server" OnClientClick="return validateStuff();" OnClick="Button1_Click" />

您的JavaScript验证:

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

如果validateStuff函数返回true,将进行postback操作,您可以在按钮单击事件中处理保存/更新逻辑:
protected void Button1_Click(object sender, EventArgs e)
{
    //save some stuff to the database

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

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

在代码后端:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    //call the RaisePostBack event 
    base.RaisePostBackEvent(source, eventArgument);

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

如果你只是想将用户带到另一个页面,你也可以这样做:
redirectToAnotherPage = function(){
    window.location.href = "somepage.aspx";
}

一个小提示 - __doPostBack 不是JS函数。当您将LinkButton添加到表单时,它会自动生成。实际上,__doPostBack 所做的是将一些数据放入隐藏字段并提交表单。因此,总的来说,您的帖子没有回答OP的问题。 - Nika G.
您是错误的。除了按钮和图像按钮之外,大多数ASP.NET控件都使用__doPostBack来执行后台提交,并且这是一种被广泛接受和可靠的技术。如果您查看OP的问题,似乎他们正在寻找从客户端触发Response.Redirect的方法,而__doPostBack是实现这一目标的完全可接受的方式。 - James Johnson
OP 没有尝试使用 Response.Redirect,我猜是这样的...而且 __doPostBack 不像 Submit() 是一个内置的 JS 函数。正如我所说,__doPostBack 在向隐藏字段写入一些数据后使用 Submit() - Nika G.
但是...你不理解我的问题。我想让JavaScript检查文本框中是否有内容..比如如果文本框A="James"和文本框B="Johnson"。如果是,我将返回true,否则我将返回false。 - Alon M
请参考以下 JavaScript 函数中如何验证文本框的示例。 - James Johnson
显示剩余13条评论

5
为了让客户端代码调用服务器端代码,你可能需要使用 AJAX。由于你提到了jQuery,它有一个非常方便的函数来进行调用。但是仅从JavaScript中进行调用只是其中一部分,你还需要在服务器上设置监听该调用的内容。如果你要使用jQuery(而不是其他选项,如 AJAX Toolkit),那么我建议不要将方法放在页面上,而应该将其作为自己的资源。我推荐使用 HttpHandler来响应AJAX调用。
重要的是要记住,这与简单地回传到页面的结构不同。使用AJAX,这些调用在页面内异步发生。因此,您应该知道的第一件事是,在这种情况下,Response.Redirect()无法工作。它将重定向AJAX调用,而不是当前打开的页面。可能有办法在ASP.NET中使用回传方法来解决这个问题,但我必须问一下...如果你所做的只是重定向,那为什么不在客户端上做呢?JavaScript完全能够胜任。您可以轻松地从服务器上进行回传后重定向,但是在JavaScript中,为什么不让JavaScript自己完成呢?

该函数只是为了解释我即将要做的事情,我想调用一个函数来注册人员到SQL,然后js将检查他们是否写得很好...如果您有任何简单的演示方式,我会喜欢,谢谢。 - Alon M
看起来你需要在提交表单之前在JavaScript中执行一些验证。你是在按钮点击时做这个吗?如果是这样,请使用OnClientClick进行验证,如果验证成功就返回true。返回true将导致postback,并且您可以在按钮点击事件中处理服务器端逻辑。 - James Johnson
@Alon M: 注册流程应该异步进行还是只验证输入?(请记住,输入应该在多个地方进行验证。使用JavaScript在页面上进行验证以获得平滑的用户体验。在网站的后端代码中进行验证以确保实际验证输入,因为任何客户端都可以更改。并在数据中进行验证(数据访问代码,数据库本身等)以保证数据完整性。)如果注册本身需要异步进行,则肯定需要一个AJAX调用。否则,简单的JavaScript就足够了。 - David
我只需要一段JavaScript代码来检查用户是否正确输入了用户名、密码、年龄等信息。当用户完成输入后,我需要调用一个C#函数来注册他(她还将检查数据库和其他所有内容)。 - Alon M
@Alon M:在Stack Overflow上这样的问题有点宽泛。具体需要异步发生什么?您可以在页面上进行UI验证。(有一个很好用的jQuery插件:http://bassistance.de/jquery-plugins/jquery-plugin-validation/)但是,您的要求开始变得有点模糊。实际注册需要异步发生吗?还是只有在发布页面时才会发生?(后者更为常见。)我们不能为您编写整个程序,但我们可以帮助您解决卡住的具体问题。 - David

3
使用 JavaScript 从客户端调用 C# 方法的一种方法是使用 webmethods
您需要在代码后台定义一个 public static 方法,并为其添加 [WebMethod] 属性。
在此示例中,我使用了一个 WebMethod 来从服务器返回当前日期时间的字符串:

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

在aspx页面中,您需要添加一个带有EnablePageMethods="true"的asp:ScriptManager:
[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>

对于Button1:

ClientIDMode="Static" 被用来使得 Button1 在客户端和服务端具有相同的ID,这样我们可以在添加客户端onclick时更容易地搜索到它。

UseSubmitBehavior="false" 是必需的,以便按下该按钮不会引起完整的回发。

在这个例子中,通过按下Button1将调用代码后台的WebMethod MyMethod,因此我们在window.onload上设置了Button1 的onclick行为:

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

地点:

PageMethods.MyMethod(myMethodCallBackSuccess, myMethodCallBackFailed);

这是一种调用服务器端代码的JavaScript方法。

我们需要定义两个回调方法,一个是成功的,另一个是失败的。

当成功时,我们会弹出一个消息框,其中包含从MyMethod返回的值:

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

当失败时,我们会弹出一条带有错误信息的消息:

function myMethodCallBackFailed(error) {
    alert(error.get_message());
}

3
您可以将C#方法转换为WebMethod,并进行调用。请参考以下链接:http://www.xdevsoftware.com/blog/post/Call-WebMethod-from-Javascript-in-ASPNET.aspx 在JavaScript中,它被称为pagemethod。
但是针对您的示例,我建议您在ASP.NET标记呈现HTML时使用asp.net标记预先填充值“pagewho?”。
例如(在JavaScript中):
GoToLink("<%= YourCodeBehindMethodReturingURLToPutHere() %>");

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

在ASP.NET中,内嵌代码和内联服务器标记是两种不同的方式来将代码插入到HTML页面中。内嵌代码适用于短小精悍的代码段,而内联服务器标记则更适合嵌入大量的服务器端代码。使用这些技术可以使代码更具可读性和易于维护。

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>

关于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
    }
}

什么都没听懂,抱歉,你能解释一下吗? - Alon M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接