如何避免功能重复

时间:2018-10-03 07:04:58

标签: c# asp.net-mvc

 if (countRefinements > 1)
    {
        if (refinementType.ToString().ToLowerInvariant() != "micro")
        {
            <div class="refinementContainer refinementmacro">
                //some functions
            </div>
        }

        else
        { 
            switch (Enumerable.Range(1, 17).Contains(countRefinements))
            {
                case true:
                    <div class="refinementContainer classIfConditionIsTrue refinementmicro">
                       //some functions
                    </div>
                    break;

                case false:
                    <div class="refinementContainer refinement@(refinementType.ToString().ToLowerInvariant())" data-dimension="@(refinementType.ToString().ToLowerInvariant())">
                        <div class="refinementContainer classIfConditionIsFalse refinementmicro">
                            //some functions
                        </div>
                    break;
                    </div>
                    break;
            }


        }
    }

我有这种情况。我需要避免将dom复制到代码中。唯一的变化是,如果开关中的条件为TRUE,则添加一个类。我该怎么解决?

2 个答案:

答案 0 :(得分:1)

引入一个变量来保存您的CSS类。然后根据您的条件附加到此变量。最后,仅渲染一次。

下面的示例(Razor)仅演示如何根据一种情况呈现“ classIfConditionIsTrue”或“ classIfConditionIsFalse”:

@{
   // TODO: handle "macro", create outer div if false
   string cssClasses = "refinementContainer refinementmicro";
   if (countRefinements >= 1 && countRefinements <= 17) {
       cssClasses += " classIfConditionIsTrue";
   }
   else {
       cssClasses += " classIfConditionIsFalse";
   }
}

<div class="@cssClasses">
    // some functions
</div>

答案 1 :(得分:0)

您可以使用Razor语法简化代码。这个想法是在将合适的类名呈现为HTML代码之前,先对其进行检查。 参考:https://docs.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c

@{
    //declare this on top of your cshtml page
    var className = "refinementContainer";

    if (countRefinements > 1 && !string.IsNullOrWhiteSpace(refinementType.ToString()))
    {
        if (refinementType.ToString().ToLower() != "micro")
        {
            className += " refinementmacro";
        }
        else if (countRefinements >= 1 && countRefinements <= 17)
        {
            className += " classIfConditionIsTrue refinementmicro";
        }
        else
        {
            className += " classIfConditionIsFalse refinementmicro";
        }
    }
}
<div class="@(className)">
   //some functions
</div>