首页 > 解决方案 > 文本颜色格式化 Razor View Engine C#

问题描述

我正在学习 C#,并且对我正在处理的问题有要求。该任务指出:

如果数组中的字符串以字母 x 开头,则<p>使用红色文本设置元素的样式。

我该怎么做呢?我了解如何设置

       <div>
            <p>@word</p>
            @if(word.Length <4) <!--anything under 4 char will be known as a short word.-->
            {
            <p>@word is a short word</p>
            }
            @elseif(word <!--beginning with c should be red-->) <!-- I don't know if "elseif" is usable or appropriate here-->
            {
            <p>@word <!-- but you know, in red--></p>
            }
      </div>

如果有人问过这个问题,我深表歉意,我自己搜索并没有找到任何东西。

标签: c#razorengine

解决方案


我假设您在这里寻求一些 CSS 建议。样式是用 CSS 完成的:https ://developer.mozilla.org/en-US/docs/Web/CSS/color 。您可以内联样式,但一般来说,您应该始终考虑使用 CSS 类。

// this normally goes into the `<head>` section of your view
<style type="text/css">
    .long-word {
        color: red
    }
</style>
// ..........................
   <div>
        <p>@word</p> 
        @if(word.Length <4) <!--anything under 4 char will be known as a short word.-->
        {
        <p>@word is a short word</p>
        }
        @elseif(word.StartsWith("x")) <!-- this is your check-->
        {
        <p class="long-word">@word</p> <!-- and this is where you apply your style  -->
        }
  </div>

推荐阅读