假设我有两个 CSS 样式,分别是 january
和 tuesday
。我想根据是否是一月和星期二将它们应用于我 View 中的某些文本字段。
选项 A:在 Controller 中执行逻辑,并将样式放在 ViewData 中。
在 Controller 中:
if( month == Month.January)
ViewBag.UserNameCssStyles = "january";
if( today == Day.Tuesday )
ViewBag.UserNameCssStyles += " tuesday";
在 View 中:
@Html.TextBoxFor(model => model.UserName, new { @class = ViewBag.UserNameCssStyles }
选项 B:在 Controller 中做逻辑并在 View 中分配样式?
在 Controller 中:
ViewBag.IsJanuary = (month == Month.January);
ViewBag.IsTuesday = (today == Day.Tuesday);
在 View 中:
@if (ViewBag.IsJanuary && !ViewBag.IsTuesday)
{
@Html.TextBoxFor(model => model.UserName, new { @class = "january" })
}
else if (!ViewBag.IsJanuary && ViewBag.IsTuesday)
{
@Html.TextBoxFor(model => model.UserName, new { @class = "tuesday" })
}
else if(ViewBag.IsJanuary && ViewBag.IsTuesday)
{
@Html.TextBoxFor(model => model.UserName, new { @class = "january tuesday" })
}
else
{
@Html.TextBoxFor(model => model.UserName)
}
我觉得这两种方式都不对。第一个选项让 Controller 与显示有关,并且还锁定了样式,因此在 View 上工作的人无法更改它们,比如添加第三个类。但第二个选项似乎只是一个“愚蠢”的观点,逻辑很繁重。
其他人通常是怎么做的?
最佳答案
选项 C:在 Controller 中执行逻辑并在 View 中分配样式,但采用更简单的方式:
在 Controller 中:
ViewBag.IsJanuary = (month == Month.January);
ViewBag.IsTuesday = (today == Day.Tuesday);
在 View 中:
@string userNameClass = string.Empty;
@userNameClass += ViewBag.IsJanuary ? "january " : "";
@userNameClass += ViewBag.IsTuesday ? "tuesday " : "";
@Html.TextBoxFor(model => model.UserName, new { @class = userNameClass })
否则您的 Controller 会因 View 问题而受到污染。除非您是 google 并且每个字节都很重要,否则空类基本上是无害的。
关于ASP.NET MVC : How do other people apply conditional CSS classes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7406467/