如何根据条件语句的结果设置可变字符串的样式?

How to style a variable string according to the result of a conditional statement?

为了简化这个问题,我写了一个基本的 if/else 语句,如果在表单发布时满足条件或 [=23],它会显示消息 "The number is correct!" =]"Sorry. The number is incorrect!"如果不满足条件。

@{
    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 标签仍​​会呈现。

还有其他方法吗?

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

//if(IsPost){
        if(num1.AsInt() == num2.AsInt()) {
            totalMessage = "The number is correct!";
        }
        else
        {
            totalMessage = "Sorry. The number is incorrect!";
        }
    //}

如@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>