简体   繁体   English

从后面的C#代码向Javascript函数传递值

[英]Pass a value to a Javascript function from C# code behind

I have this javascript function in a .aspx file. 我在.aspx文件中有此javascript函数。

<script>
    function somefun(value)
    {

    }
<script> 

I'm calling and passing a value to that function inside the code-behind class. 我在代码隐藏类内调用该函数并将值传递给该函数。

ScriptManager.RegisterStartupScript(this, typeof(string), "Passing", String.Format("somefun('{0}');", filePath1), false);        

But when it runs, the function doesn't work properly. 但是,当它运行时,该功能无法正常工作。 I'm getting an printed output like this 我得到这样的打印输出

" somefun(the content of the variable) " somefun(变量的内容)

What would be the issue? 会是什么问题?

Try with: 尝试:

ScriptManager.RegisterStartupScript(this, typeof(Page), "Passing", String.Format("somefun('{0}');", filePath1), false);        

Source: http://msdn.microsoft.com/it-it/library/bb350750(v=vs.110).aspx 来源: http : //msdn.microsoft.com/it-it/library/bb350750(v=vs.110).aspx

First, I like to use a function to Execute Javascript code on the client browser... 首先,我喜欢使用一个函数在客户端浏览器上执行Javascript代码...

#region ExecuteJavascript
private int _intScriptIndex = 0;
private void ExecuteJavascript(string strScript)
{
    System.Web.UI.ScriptManager.RegisterStartupScript(Page, typeof(Page), "ExecuteScript" + _intScriptIndex++, strScript, true);
}
#endregion

Now I just call JavaScript like this... 现在,我像这样调用JavaScript ...

ExecuteJavascript("alert('test');");

To call a function with variables you would do this... 要使用变量调用函数,您可以执行此操作...

ExecuteJavascript(String.Format("somefun('{0}');", filePath1));

That should do it. 那应该做。 The key to why mine works and yours doesn't is probably in the properties of RegisterStartupScript, notice that I pass Page and typeof(Page) where you put string. 我的工作原理和我的工作原理不起作用的关键可能在于RegisterStartupScript的属性,请注意,我在放置字符串的地方传递了Page和typeof(Page)。

请尝试这个

ScriptManager.RegisterStartupScript(this, typeof(string), "Passing", "somefun('" + filePath1 + "');" ,false); 

This should work. 这应该工作。

C# code: C#代码:

String vls_variable = "TestData";
ScriptManager.RegisterStartupScript(this, typeof(string), "script1", "SampleJSFunction('" + vls_variable + "');", true);

JavaScript function: JavaScript函数:

function SampleJSFunction(variable) 
{  
    var data = variable;
    alert("working");            
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM