Search code examples
c#javascriptasp.net-mvc-3razor

C# 'if' key word inside <script> tag in razor view


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?


Solution

  • 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.