Skip to content Skip to sidebar Skip to footer

Mvc: Use String Variables Of A View As Parameter To A Javascript Function Call

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 java

Solution 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">
    functionjavascriptFunction(first,second)
    {
        alert(first+' '+second);
    }

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

Using Razor within javascript

Solution 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

Post a Comment for "Mvc: Use String Variables Of A View As Parameter To A Javascript Function Call"