简体   繁体   中英

Pass a value to a Javascript function from C# code behind

I have this javascript function in a .aspx file.

<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) "

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

First, I like to use a function to Execute Javascript code on the client browser...

#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...

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.

请尝试这个

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

This should work.

C# code:

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

JavaScript function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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