我想要一个条件(“myBool”)为真的 html 代码:
<div>
<fieldset>
<legend>
@sometext
</legend>
... other stuffs
</fieldset>
<div>
这个是假的:
<div>
<b>
@sometext
</b>
... other stuffs
<div>
我不知道要写两次相同的代码(“其他东西”),所以我尝试了这个:
<div>
@if(myBool)
{
<fieldset>
<legend>
}
else
{
<b>
}
@sometext
if (myBool)
{
</legend>
}
else
{
</b>
}
...other stuff
if (myBool)
{
</fieldset>
}
</div>
但是我得到了编译错误。
你知道我如何可以做我想做的事而不必做那样的事情吗:
@if(myBool)
{
<div>
<fieldset>
<legend>
@sometext
</legend>
... other stuffs
</fieldset>
<div>
}
else
{
<div>
<b>
@sometext
</b>
... other stuffs
<div>
}
谢谢。
最佳答案
以下可能会使用 @:
运算符。
当您在代码块内时,无论是因为控制结构(如下面给出的示例)还是因为您已经明确定义了一个代码块,您都可以输出纯文本,方法是在 @ 字符前加上 :(冒号)性格。
<div>
@if (someCondition)
{
@:<fieldset>
@:<legend>
}
else
{
@:<b>
}
@sometext
if (someCondition)
{
@:</legend>
}
else
{
@:</b>
}
... other stuffs
@if (someCondition)
{
@:</fieldset>
}
</div>
或者您也可以尝试以下操作:
<div>
@Html.Raw(someCondition ? "<fieldset><legend>" : "<b>")
@sometext
@Html.Raw(someCondition ? "</legend>" : "</b>")
... other stuffs
@if (someCondition)
{
@:</fieldset>
}
</div>
关于html - MVC/ Razor : Conditional nested html tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14879864/