0

How do I call a javascript function from within razor markup in a cshtml view? Basically I want to do something like this (which doesnt work):

Javascript file being included on the page has a method like this:

<script type="text/javascript">
function doesThisWork() {
return true;
}
</script>

View has code block similar to this:

<div>
@if(doesThisWork()) {
<span> this DOES work!!! </span>
}
else
{
<span> this does NOT work!!! </span>
}
</div>
Yiyi You
  • 16,875
  • 1
  • 10
  • 22
Randy
  • 71
  • 1
  • 8
  • take a look at https://stackoverflow.com/questions/2709978/call-javascript-from-mvc-controller-action – Patrick Hume Jul 03 '22 at 23:31
  • You cannot call js in html.Can you explain more about what you want to do?Maybe you can use different way to do it. – Yiyi You Jul 04 '22 at 02:37
  • Basically what I'm trying to do is this: Render one of two html blocks with values coming from a CMS depending on a value that's being read in from a cookie. This has to be done on the front end so if the user adjusts their cookie setting, the appropriate html block should be swapped out without having to reload the page. – Randy Jul 04 '22 at 14:32

1 Answers1

0

You cannot call the javascript function on the server side but it can be achieved as below code.

Html:

//Declare a div where you want display html
<div id="bindHtml"></div>

Script:

<script type="text/javascript">

  //On pageload call function and display Html based on your function return.
   $(document).ready(function(){
      let htmlContent = "";
       if(doesThisWork()){
          htmlContent = "<span> this DOES work!!! </span>";
       }else{
          htmlContent = "<span> this does NOT work!!! </span>";
       }
       //Bind Html to declared div in the Html
       $("#bindHtml").append(htmlContent);
    });

    function doesThisWork() {
       return true;
    }
</script>
Ram Anugandula
  • 582
  • 4
  • 15
  • Thanks for your answer but I specifically need to be able to check the return value of the javascript in the if then statement in razor. – Randy Jul 04 '22 at 14:22
  • `I specifically need to be able to check the return value of the javascript in the if then statement in razor`I'm afraid not.You'd better replace html with js as Ram Anugandula shown in his answer. – Yiyi You Jul 06 '22 at 06:31