How to embed c# code in javascript on cshtml MVC3 Razor page
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 bl开发者_开发知识库ock 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
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>
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>
精彩评论