问题
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
回答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
回答2:
you could load some variables using the answer from this link and pass them into your function.
ASP.NET MVC using ViewData in javascript
来源:https://stackoverflow.com/questions/14223035/mvc-use-string-variables-of-a-view-as-parameter-to-a-javascript-function-call