MVC: Use string variables of a view as parameter to a javascript function call

大城市里の小女人 提交于 2019-12-11 17:44:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!