asp.net-mvc 在 CSHTML 页面中实现 switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7347989/
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
Implementing a switch statement in a CSHTML page
提问by Marianne
I'm trying to do something different. I have a view that contains an Id. Based on the value of the Id I want to change my heading that appears. Something like:
我正在尝试做一些不同的事情。我有一个包含 Id 的视图。根据 Id 的值,我想更改出现的标题。就像是:
@{ switch id
case "test": @;<h1>Test Site</h1>
case "prod": @:<h1>Prod Site</h1>
break;
}
I have quite a lot of case conditions so I though use of case would be best. Can anyone suggest how I can do this and get it to work? I am getting a lot of syntax errors so I think maybe it's not coded well.
我有很多案例条件,所以我认为最好使用案例。谁能建议我如何做到这一点并让它发挥作用?我收到了很多语法错误,所以我想可能它没有很好地编码。
回答by Joel Etherton
Your switch needs to be completely enclosed in a block and it needs to be "broken" properly:
您的开关需要完全封闭在一个块中,并且需要正确“断开”:
// Use the @{ } block and put all of your code in it
@{
switch(id)
{
case "test":
// Use the text block below to separate html elements from code
<text>
<h1>Test Site</h1>
</text>
break; // Always break each case
case "prod":
<text>
<h1>Prod Site</h1>
</text>
break;
default:
<text>
<h1>WTF Site</h1>
</text>
break;
}
}
Because the <h1>tags are enclosed html blocks by themselves, you may not need the <text>blocks for separation. It's just my habit to include them.
因为<h1>标签是自己封闭的 html 块,所以您可能不需要这些<text>块进行分隔。包括它们只是我的习惯。
回答by yoel halb
@switch (id)
{
case "test": <h1>Test Site</h1>
break;
case "prod": <h1>Prod Site</h1>
break;
}
There is no need to enclose the entire switch statement in a @{}block, (unlike Joel Etherton's post)
无需将整个 switch 语句包含在一个@{}块中,(与 Joel Etherton 的帖子不同)
Your errors are basically regular syntax errors and have nothing to do with razor;
您的错误基本上是常规语法错误,与 razor 无关;
the variable wasn't in parenthesis
the body of switch wasn't in brackets
no "break" after the first statement.
变量不在括号中
开关的主体不在括号中
第一个语句后没有“中断”。
回答by Kenny Evitt
This doesn't answer your question, as indicated by the question's title, but it does solve the problem you described in the body of the question.
正如问题标题所示,这不会回答您的问题,但它确实解决了您在问题正文中描述的问题。
Use a view model class as the view's model and add a method that includes the switchstatement. Then just call the method from the view via @Model.MethodWithSwitchStatement(). [The idcan be saved in the view model object.]
使用视图模型类作为视图的模型,并添加一个包含该switch语句的方法。然后只需通过视图从视图中调用该方法@Model.MethodWithSwitchStatement()。[id可以保存在视图模型对象中。]
回答by McClint
@{
String txt;
switch (id) {
case "test":
txt = "Test";
break;
case "prod":
txt = "Prod";
break;
default:
txt = "WTF";
}
}
<h1>@txt Site</h1>
The Most Concise: Less redundant or repetitive code and markup.
最简洁:减少冗余或重复的代码和标记。

