Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
How can I call a javascript function within a view(cshtml) and pass some string variables (defined in the view)to be used as parameters for the function call?

Say the function javascriptFunction uses 2 parameter. I will usually call it as
JavaScript
javascriptFunction('param1', 'param2')
But now I want to pass it some variables.

HTML
string y = "this is a string"
string x = "another"
javascriptFunction(y, x)

I have tried
JavaScript
javascriptFunction(@y, @x)
JavaScript
javascriptFunction('@y', '@x')
but these do not work
Posted
Comments
Member 8044586 8-Jan-13 17:29pm    
javascriptFunction('@y', '@x') gives me a syntax error during compilation

1 solution

You need to pass the values in through a model, then @Model.X and @Model.Y will work. Where do x and y come from ? If they are javascript variables, then remove the @, which tells the compiler to use Razor, when you want local values.
 
Share this answer
 
Comments
Member 8044586 8-Jan-13 17:43pm    
x and y are variables derived in my view. I tried creating passing the values to the model and calling @Model.X but got the same error. It is a syntax error.
Christian Graus 8-Jan-13 17:47pm    
Perhaps if you told us what the error is ? And the actual code that creates them and where it lives ?
Member 8044586 8-Jan-13 17:51pm    
The code is <input type="button" önclick="javascript: function('param1', @Model.temp);" value="Test" />. The error simply says: Syntax error with red markings before the @symbol and after closing the parentheses. So the markings surround @Model.temp)
Christian Graus 8-Jan-13 18:08pm    
You do need quotes. '@Model.temp'. The value will get rendered without quotes. This is a run time error ?
Christian Graus 8-Jan-13 18:09pm    
Also, as you have quotes, param1 will be passed as "param1", not the value in a param named that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900