how would I do the equivalent of this embedded in javascript on an MVC2 aspx page:

if (('<%= Model.SomeFunctionEnabled %>' == 'True') and also a whole function code block on a Razor view page (cshtml) in MVC3?

Something like :

@{ foreach(var d in Model.Employees) { .... } }

Which works fine when embedded in the html part of the view page. Thanks

share|improve this question

2 Answers

up vote 9 down vote accepted

Why testing on the client side when you could do this on the server side and include the javascript to act accordingly if the test succeeds:

<script type="text/javascript">
    @if (Model.SomeFunctionEnabled) {
        <text>
        // Put your javascript code here
        alert('the function is enabled');
        </text>
    }
</script>
share|improve this answer
Thanks Darin, sometimes I want to keep the display code in the view. However, I've realised that its just VS' syntax highlighter which doesn't work properly for this - its actually fine! – stan4th Mar 4 '11 at 15:12
@stan4th, OK, but in your example in the if statement you were mixing server side code with javascript making it difficult to read. That's why I suggested you an improvement. – Darin Dimitrov Mar 4 '11 at 15:15

If you want to execute the logic in JavaScript:

if ('@Model.SomeFunctionEnabled' == 'True') {
}

But this results in a condition that always evaluates to the same outcome. So you are better with Darin's answer to do the whole testing on the server.

If your test is however something dynamic like this, that cannot be executed on the server. You can get the contents of your C# variable by using a @ sign.

@{
    var elementID = GetMyGeneratedElementID();
}

<div id="@elementID">...</div>
<script>
   function MyAmazingJavascriptElementHandler() {
       if ($("#@elementID").SomeTest()) {
          DoMyAmazingJavascript();
       }
   }
</script>
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.