Call JavaScript function from c# code in cshtml
-
Is it possible to call a javascript function in a cshtml, in the @{} section, and the javascript function is defined in the script section of the cshtml. Thanks
No, your cshtml is compiled and executed as .net code on the server, the result is that it generates html, that html is then sent to the client browser to be executed and the client browser can interpret and execute javascript. So you can't run javascript in your views as the javascript doesn't yet technically exist.
-
No, your cshtml is compiled and executed as .net code on the server, the result is that it generates html, that html is then sent to the client browser to be executed and the client browser can interpret and execute javascript. So you can't run javascript in your views as the javascript doesn't yet technically exist.
-
I have a list passed on to the view from the controller through a viewbag. so if the viewbag has the list, then execute a javascript function that is defined in the script section of the page. what is the other option?
<script type="text/javascript">
function myFunc() {
alert('Hello');
}
</script>@if (ViewBag.MyList != null)
{
<script>myFunc();</script>
}Note the order is important, js is interpreted in order so you can't call functions that have not yet been defined.