[英]Call JavaScript function (in aspx) on aspx.cs using a button
我有這個aspx:
<body>
<div>
<script type="text/javascript">
function NewPage() {
document.location.href = "http://www.nextservice.pt/"
}
</script>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Btn2" runat="server" Text="OK" onclick="Button2_Click" />
CODE1: <asp:Label ID="Label1" runat="server" Text="Label" ForeColor="#CC0000" />
</form>
</div>
</body>
我正在使用Web表單,但我不會在aspx.cs上調用此按鈕
public partial class SITE_TESTER : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click (object sender, EventArgs e)
{
string code = TextBox1.Text.ToString();
if (!verifyCode(code)) // comparing users from table
{
Label1.Text = "Not Exists"; //for invalid code
}
else
{
Label1.Text = "Exist"; //for sucsseful code
/*
I Wont call my JavaScript Function here!!!!
*/
}
}
}
您可以通過以下方式從asp.net的服務器端調用javascript方法:
protected void button_Click(object sender , EventArgs e)
{
string jsMethodName= = "NewPage()";
ScriptManager.RegisterClientScriptBlock(this, typeof(string), "uniqueKey", jsMethodName, true);
//or
//ScriptManager.RegisterStartupScript(this, GetType(), "NewPage()", false);
}
您可以使用ScriptManager.RegisterStartupScript
或ScriptManager.RegisterClientScriptBlock
因此,下面將解釋兩者之間的區別:
假設我們有一個帶有以下表單標記的.aspx頁面:(行號僅供參考)
1. <form id="Form1" runat="server">
2. ..
3. ..
4. ..
5. </form>
現在,讓我們看一下每種方法的主要區別:
Page.RegisterClientScriptBlock()
: Page.RegisterClientScriptBlock()
將在第2 Page.RegisterStartupScript()
之前插入腳本塊 Page.RegisterStartupScript()
將在第4行之后插入腳本。
B. Page.RegisterClientScriptBlock()
通常應用於封裝在函數中的腳本。 (因此,“ block”一詞) Page.RegisterStartupScript()
可以用於任何腳本,即使它不在函數中。
C. Page.RegisterClientScriptBlock()
應該用於不需要在頁面加載時運行的函數。 Page.RegisterStartupScript()
應該用於必須在Page Load上運行的腳本。
D. Page.RegisterClientScriptBlock()
應該用於不需要創建表單元素的腳本。 Page.RegisterStartupScript()
應該用於需要創建表單元素並使用對它們的引用的腳本。
請注意,所有4個差異本質上都是彼此相關的(它們建立在前一個之上)。 放在一行中的差異有時可能太微妙了。
您可以添加一個腳本,該腳本將在頁面加載到瀏覽器時執行:
Page.RegisterStartupScript("unique_key", "<script type=\"text/javascript\">NewPage()</script>"); // but this is deprecated function
或像這樣:
ClientScript.RegisterClientScriptBlock(this.GetType(), "unique_key", "NewPage()", true);
但是,如果您只是想進行重定向(從NewPage函數可以看到),則可以執行以下操作:
Response.Redirect("http://www.example.com");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.