[英]Call javascript and c# method with one click
我在javascript中有一個方法,在c#中有一個方法,現在單擊一個按鈕,我想同時調用它們。
首先,我想調用名為'Find_Direction'
的c#方法,因為它可以輸入onclick,然后在名為calcRoute
的javascript方法之后調用。
我正在嘗試,但是沒有運氣:
<asp:Button id="Button1" UseSubmitBehavior="False" value="GetDirections" onclick="calcRoute" OnClientClick="Find_Direction" runat="server"/>
彈出以下錯誤:
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'ASP.findroute_aspx' does not contain a definition for 'calcRoute' and no extension method 'calcRoute' accepting a first argument of type 'ASP.findroute_aspx' could be found (are you missing a using directive or an assembly reference?)
您正在onClick事件中指定javascript函數名稱。 所以放在這里C#函數名稱
C#代碼:
protected void Find_Direction (object sender, EventArgs e)
{
// do your work
// Register your javascript function
Page.ClientScript.RegisterStartupScript(this.GetType(), "script", " <script>calcRoute();</script>");
}
您的標記:
<asp:Button id="Button1" value="GetDirections" onclick="Find_Direction" runat="server"/>
情況2:先在服務器端函數之前調用javascript函數
Javascript功能
function calcRoute() {
alert('test')
return true;
}
您的標記
<asp:Button id="Button1" value="GetDirections" onclick="Find_Direction " OnClientClick="return Find_Direction()" runat="server"/>
這樣,您可以先調用javascript函數,然后再調用服務器端,但是請確保從javascript函數返回true來調用服務器端函數。
我希望,現在您可以解決您的問題。 :)
您需要在代碼隱藏(aspx.cs或aspx.vb文件)中的事件處理程序calcRoute
。
如果希望JS首先執行,則應該能夠按照自己的方式進行操作,其中OnClientClick指向JS函數,OnClick指向C#/ VB方法(事件處理程序)。
如果要確保在C#代碼之后調用JS,則應處理對后端的單擊,然后通過注冊啟動腳本將JS發送回瀏覽器。 除非您使用更新面板,否則這將導致完整的回發。 在事件處理程序中,可以使用Page.RegisterStartupScript
注冊啟動腳本,以將javascript命令發送回瀏覽器。 在這種情況下,您根本不會使用OnClientClick。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.