[英]Calling Javascript function from code behind ASP.NET
I'm attempting to call a javascript method in its own file from code behind on a button click. 我试图通过单击按钮后的代码在其自己的文件中调用javascript方法。
aspx file aspx文件
protected void Next_Click(object sender, EventArgs e)
{
if (hidden.Value == "")
{
Response.Write(@"<script language='javascript'>drawImage();</script>");
}
}
js file js文件
function drawImage() {
context.drawImage(video, 0, 0, 320, 240);
var imgBase = canvas.toDataURL('image/jpeg');
document.getElementById("hidden").value = imgBase;
}
The problem is that this wont call the draw image method, i suspect it's cause the js file is its own file but i'm not sure. 问题是,这不会调用draw image方法,我怀疑这是因为js文件是其自己的文件,但我不确定。
Any help you could give would be greatly appreciated. 您能提供的任何帮助将不胜感激。
see http://msdn.microsoft.com/de-de/library/z9h4dk8y.aspx 参见http://msdn.microsoft.com/de-de/library/z9h4dk8y.aspx
try this 尝试这个
string jquery = "drawImage();"
ClientScript.RegisterStartupScript(typeof(Page), "a key",
"<script type=\"text/javascript\">"+ jquery +"</script>"
);
I presume you already included the script file in your page. 我想您已经在页面中包含了脚本文件。
If you require the postback, you need ClientScriptManager.RegisterStartupScript Method (Type, String, String, Boolean) .. 如果需要回发,则需要ClientScriptManager.RegisterStartupScript方法(类型,字符串,字符串,布尔值) 。
protected void Next_Click(object sender, EventArgs e)
{
if (hidden.Value == "")
{
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(this.GetType(), 'startupScript', 'drawImage();', true);
}
}
You can call the function from your button itself, without the postback. 您可以从按钮本身调用该函数,而无需回发。
<asp:Button runat="server" ID='next' OnClientClick="return drawImage();" />
and in the script 并在脚本中
function drawImage() {
if(document.getElementById("hidden").value != undefined || document.getElementById("hidden").value != "")
{
context.drawImage(video, 0, 0, 320, 240);
var imgBase = canvas.toDataURL('image/jpeg');
document.getElementById("hidden").value = imgBase;
return false;
}
}
1). 1)。 If the function is stored in external file (eg
MyScript.js
) then you should include it in the <head>
section of the web page and add onclick
event to the button, like: 如果函数存储在外部文件(例如
MyScript.js
)中,则应将其包含在网页的<head>
部分中,然后将onclick
事件添加到按钮,例如:
ButtonName.Attributes.Add("onclick", {YourFunction});
in Page_Load
event. 在
Page_Load
事件中。
2) Another approach is to assign the entire javascript function to a string variable and then pass it instead of {YourFunction} prefixed with javascript:
. 2)另一种方法是将整个javascript函数分配给一个字符串变量,然后将其传递,而不是以
javascript:
为前缀的{YourFunction}。 In this case you don't even need the external file. 在这种情况下,您甚至不需要外部文件。
Hope it will help. 希望它会有所帮助。 My best, Alex
我最好的Alex
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.