javascript - 一键调用javascript和c#方法

标签 javascript asp.net button

我有一个 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 来调用服务器端函数。

我希望,现在您可以解决您的问题。 :)

关于javascript - 一键调用javascript和c#方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184097/

相关文章:

javascript - 使用 jQuery 的 Location header 在 POST 之后重定向

asp.net - 使用 Paypal 订阅(Netflix 风格)

javascript - 如何捕获动态创建的按钮的点击? jQuery

android - 垂直和水平居中文本,下方并排放置 2 个按钮

android - 如何在 Android 中将菜单添加到按钮

javascript - jquery根据字符计算字体大小

javascript - 如何设置临时cookie?

javascript - 将带有数组的数组映射到数组中

javascript - ASP.NET MVC - 将包含数组的 FormData 映射到模型类

javascript - 如何在 ASP.NET 中创建登录页面的重定向?