MVC/Razor:条件嵌套html标记
我希望有一个条件(“myBool”)为真的html代码:MVC/Razor:条件嵌套html标记,html,asp.net-mvc,razor,Html,Asp.net Mvc,Razor,我希望有一个条件(“myBool”)为真的html代码: <div> <fieldset> <legend> @sometext </legend> ... other stuffs </fieldset> <div> @一些文字 ... 其他东西 当它是假的时候: <div> <b> @sometext </b> ..
<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>
@如果(myBool)
{
}
其他的
{
}
@一些文字
如果(myBool)
{
}
其他的
{
}
…其他东西
如果(myBool)
{
}
但我有编译错误
你知道我怎么能做我想做的而不必做那样的事吗
@if(myBool)
{
<div>
<fieldset>
<legend>
@sometext
</legend>
... other stuffs
</fieldset>
<div>
}
else
{
<div>
<b>
@sometext
</b>
... other stuffs
<div>
}
@if(myBool)
{
@一些文字
…其他东西
}
其他的
{
@一些文字
…其他东西
}
谢谢。使用
@:
运算符可能会执行以下操作。
当您位于代码块内部时,无论是因为控件结构(如下面给出的示例)还是因为您已经明确定义了一个控件结构,您都可以通过在前缀中加@字符和:(冒号)字符来输出纯文本
<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.Raw(someCondition?:“”)
@一些文字
@Html.Raw(someCondition?:“”)
... 其他东西
@如果(某些条件)
{
@:
}
谢谢,我不认识@:接线员!非常感谢@Darin Dimitrov也为我做了完美的工作。谢谢我真的很感激你,达林,你是我的英雄:)救了我一天,如果可以的话,我希望得到+10点,还有一个问题:@:和@Html.Raw()有什么不同吗?