为简化此问题,我写了一条基本的if / else语句,如果在表单发布中满足条件或显示“对不起”,则显示消息“数字正确!” 。该数字不正确!” 如果不满足条件。
@{
Layout = "/shared/_SiteLayout.cshtml";
var num1 = Request["text1"];
var num2 = "4";
var totalMessage = "";
if (IsPost)
{
if(num1.AsInt() == num2.AsInt())
{
totalMessage = "The number is correct!";
}
else
{
totalMessage = "Sorry. The number is incorrect!";
}
}
}
<br>
<br>
<br>
<br>
<br>
<div style="margin: 0 40px 0 40px">
<p style="font-weight: bold;">@totalMessage</p>
<br>
<p>4 + what = 8? <strong>Add the missing number</strong>.</p>
<form action="" method="post">
<label for="text1">Add Number Here:</label>
<input type="text" name="text1" />
<input type="submit" value="Add" />
</form>
</div>
问题:如果不满足条件,如何在不同颜色下设置变量的样式?
@totalMessage
我可以通过在语句和标记中使用第二个变量,然后将变量包装在HTML标记中并添加CSS样式来解决该问题。
var totalMessage2 = "";
totalMessage2 = "Sorry. The number is incorrect!";
<style>
.incorrect {
color: red;
}
</style>
<span class="incorrect">@totalMessage2</span>
但是,如果满足条件,则仍会显示空白HTML标记。
还有另一种方法吗?
答案 0 :(得分:1)
如@kenci所述,您可以执行以下操作:
@{
Layout = "/shared/_SiteLayout.cshtml";
var num1 = Request["text1"];
var num2 = "4";
var totalMessage = "";
bool isCorrectNumber = false;
if (IsPost)
{
if (num1.AsInt() == num2.AsInt())
{
totalMessage = "The number is correct!";
isCorrectNumber = true;
}
else
{
totalMessage = "Sorry. The number is incorrect!";
isCorrectNumber = false;
}
}
}
<br>
<br>
<br>
<br>
<br>
<div style="margin: 0 40px 0 40px">
@{
if (isCorrectNumber)
{
<span class="correct">@totalMessage</span>
}
else
{
<span class="incorrect">@totalMessage</span>
}
}
<br>
<p>4 + what = 8? <strong>Add the missing number</strong>.</p>
<form action="" method="post">
<label for="text1">Add Number Here:</label>
<input type="text" name="text1" />
<input type="submit" value="Add" />
</form>
</div>
答案 1 :(得分:0)
注释IsPost
,它将起作用。您只应在控制器中检查IsPost
。
//if(IsPost){
if(num1.AsInt() == num2.AsInt()) {
totalMessage = "The number is correct!";
}
else
{
totalMessage = "Sorry. The number is incorrect!";
}
//}