0

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 javascriptFunction('param1', 'param2') . But now I want to pass it some variables.

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

I have tried javascriptFunction(@y, @x), javascriptFunction('@y', '@x') but this does not work

jpo
  • 3,959
  • 20
  • 59
  • 102

2 Answers2

1

You have to distinguish between javascript code and server-side code. Also encode your javascript strings:

@{
string y = "this is a string";
string x = "another";
}

<script type="text/javascript">
    function javascriptFunction(first,second)
    {
        alert(first+' '+second);
    }

    javascriptFunction(@Html.Raw(Json.Encode(y)), @Html.Raw(Json.Encode(x)));
</script>

Using Razor within javascript

Community
  • 1
  • 1
semao
  • 1,757
  • 12
  • 12
0

you could load some variables using the answer from this link and pass them into your function.

ASP.NET MVC using ViewData in javascript

Community
  • 1
  • 1
Modika
  • 6,192
  • 8
  • 36
  • 44