23

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?

1
  • 1
    Interesting tidbit: the <script> breaks this question in the RSS feed. Commented Oct 6, 2011 at 15:55

2 Answers 2

56

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:

  • usage of ViewData.ModelState.IsValid to test if there are modelstate errors
  • usage of the special <text> to indicate to the razor parser to use the text as is
  • usage of the $ function as I suppose this is jQuery code
  • properly closing quotes around javascript strings
  • usage of the type="text/javascript" attribute on the script tag.
Sign up to request clarification or add additional context in comments.

2 Comments

You are right about your comments, I just gave a simple example (With stupid errors), checking the <text> now
As always your answer was helpful!
2

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').

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.