所以,我有一个看起来像这样的 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?");
}
再次感谢阿隆。 :)
编辑:
这是我目前正在使用的完整代码:
<%@ 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。有帮助吗?
最佳答案
您可以在脚本中使用 __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,将发生回传,您可以在按钮单击事件中处理保存/更新逻辑:
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";
}
关于c# - 在 Asp.net webforms 中从 JavaScript/JQuery 调用 C# 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7444483/