ASP.NET MVC : How do other people apply conditional CSS classes?

标签 asp.net css asp.net-mvc asp.net-mvc-3

假设我有两个 CSS 样式,分别是 januarytuesday。我想根据是否是一月和星期二将它们应用于我 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/

相关文章:

c# - 如何优雅地检查 Gravatar 或第三方网站是否正常运行?

c# - ASP.NET C# : JavascriptSerializer could not be found

html - 在 css 中添加颜色标签

html - 如何在 Bootstrap 卡中显示多个水平图像?

c# - 下拉选择的值应该作为字符串发布到 Controller

c# - 如何调试 ASP.NET 中的 404 错误?

asp.net - 我可以使用 owin 和 oauth 提供商的 asp.net 成员(member)资格吗?

css - IE7 图像 float 错误

c# - 为什么 HTML.TextArea 之前需要一个@?

javascript - 使用 AJAX 将基于 JSON 的远程数据导入 Select2