Monday, May 20, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  171] [ 3]  / answers: 1 / hits: 17438  / 13 Years ago, thu, october 6, 2011, 12:00:00

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?


More From » c#

 Answers
5

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.


[#89754] Wednesday, October 5, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;