Reputation: 150253
I'm trying to write the following code inside ASP.Net-MVC razor view but the page won't compile.
<script>
@(if (Model.IsValid))
{
("#ErrorMessage).text("Error");
}
else
{
("#Registration).text("Done!");
}
</script>
There are workarounds that I did to achieve that operation, but is there a simple way?
Upvotes: 23
Views: 18301
Reputation: 377
Here's a workaround that may look a little better:
<script>
var modelIsValid = '@ViewData.ModelState.IsValid' == '@true';
if(modelIsValid)
{
$("#ErrorMessage").text("Error");
}
else
{
$("#Registration").text("Done!");
}
</script>
Using '@true' makes sure that the true string is always correct (rather than hardcoding it like 'True').
Upvotes: 2
Reputation: 1038720
Try like this:
<script type="text/javascript">
@if (ViewData.ModelState.IsValid)
{
<text>$('#ErrorMessage').text('Error');</text>
}
else
{
<text>$('#Registration').text('Done!');</text>
}
</script>
Things to notice:
ViewData.ModelState.IsValid
to test if there are modelstate errors<text>
to indicate to the razor parser to use the text as is$
function as I suppose this is jQuery codetype="text/javascript"
attribute on the script tag.Upvotes: 56