为了简化这个问题,我编写了一个基本的 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 标记仍会呈现。
还有另一种方法可以做到这一点吗?