0

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?

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This gives the same result.
0

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.

2 Comments

Yeah, ExecuteJavascript("alert('test');"); works. But the ExecuteJavascript(String.Format("somefun('{0}');", filePath1)); gives an error. Error: Unable to get property 'SetVariable' of undefined or null reference
somefun('Test.txt'); This is syntactically correct, the SetVariable error you are getting must be a Javascript error unrelated to the code executing in .Net.
0

please try this

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

1 Comment

string concatenation with + is functionally equivalent to string.format. Your suggestion will make no difference
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.