为了简化这个问题,我编写了一个基本的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标记仍会呈现。
还有另一种方法吗?
正如@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>
评论IsPost
它会工作。你应该只在控制器中检查IsPost
。
//if(IsPost){
if(num1.AsInt() == num2.AsInt()) {
totalMessage = "The number is correct!";
}
else
{
totalMessage = "Sorry. The number is incorrect!";
}
//}