javascript 剃刀视图中<script>标签内的C#'if'关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7676851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:54:32  来源:igfitidea点击:

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

c#javascriptasp.net-mvc-3razor

提问by gdoron is supporting Monica

I'm trying to write the following code inside ASP.Net-MVC razor view but the page won't compile.

我正在尝试在 ASP.Net-MVC razor 视图中编写以下代码,但该页面无法编译。

<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?

我做了一些变通方法来实现该操作,但有没有一种简单的方法?

回答by Darin Dimitrov

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.IsValidto 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.
  • 的使用ViewData.ModelState.IsValid,以测试是否有错误的ModelState
  • 使用 special<text>来指示 razor 解析器按原样使用文本
  • $函数的使用,因为我认为这是 jQuery 代码
  • 正确关闭javascript字符串周围的引号
  • 使用type="text/javascript"脚本标签上的属性。

回答by Bochu

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

使用 '@true' 可确保真正的字符串始终正确(而不是像 'True' 那样对其进行硬编码)。