我有一个 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/