0

为了简化这个问题,我编写了一个基本的 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? &nbsp; <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 标记仍会呈现。

还有另一种方法可以做到这一点吗?

4

2 回答 2

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? &nbsp; <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>
于 2019-04-16T20:31:35.130 回答
0

注释掉IsPost它会起作用。您应该IsPost只检查控制器。

//if(IsPost){
        if(num1.AsInt() == num2.AsInt()) {
            totalMessage = "The number is correct!";
        }
        else
        {
            totalMessage = "Sorry. The number is incorrect!";
        }
    //}
于 2019-04-16T13:01:17.447 回答