call javascript function from c# code in cshtml

capri

Active member
Joined
Jun 16, 2015
Messages
42
Programming Experience
5-10
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 same cshtml.


Thanks
 
The javascript is executed in the browser at the client end. The Razer is executed by the web server at the server end. JavaScript can be executed on the server but not from a client script file. What is it that you're actually trying to achieve?
 
I take a list of items from the controller to the view with ViewBag. If the ViewBag contains items more than one, then I want to call a function in javascript defined in the script section of the cshtml file to enable few controls.
 
That's not how it works. Either you do it server-side with Razor code or client-side in JavaScript; not both. If you want to do it server-side then you write some Razor code to determine whether there is more than one item in the collection and then you pass the appropriate values to your HTML helpers or tag helpers to construct the HTML with the controls in the appropriate state. If you want to do it in JavaScript then you do it client-side after the document has loaded. I would tend to lean toward the first option, doing as much as possible before the document loads.
 
Back
Top Bottom