使用 cshtml/c#/css/javascript 优化网页样式

Optimize web page styling with cshtml/c#/css/javascript

我正在使用 cshtml/c#/css/javascript 的组合来创建一个网页,我是全新的,所以欢迎任何提示。

C# 文件创建部分 class,这是一个示例片段

[Required]
[Display(Name = "First Name *")]        //First Name * is displayed on actual page
public string FirstName{ get; set; }

cshtml 文件创建所有必要的容器、标签和段落。 css 包含所有样式。 javascript 增强了网页功能。

所以,这是一个交易:我需要添加 *,对于所有必需的元素,它应该都是红色的。我可以遍历所有可能的页面并手动将它们添加到每个元素,但我想是否可以优化代码。

是否可以创建类似于下面的伪代码的东西?

if variable has a required flag set to it //from c# file
    add stylized red * next to the label 

任何帮助将不胜感激!

更新

我修改了下面提供的文章中的代码,但是,这是我一直遇到的另一个问题。这是我的助手修改后的代码:

public static MvcHtmlString EditorEntryFor<TModel, TValue>(
      this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
  {
     return BuildFormEntry(html.LabelWithRequiredMarkerFor(expression),
         html.EditorFor(expression), html.ValidationMessageFor(expression));
     //return BuildFormEntry(html.LabelWithRequiredMarkerFor(expression),
     //    html.TextAreaFor(expression), html.ValidationMessageFor(expression));
  }

private static MvcHtmlString LabelWithRequiredMarkerFor<TModel, TValue>(
      this HtmlHelper<TModel> html,
      Expression<Func<TModel, TValue>> expression)
  {
     var label = html.LabelFor(expression);
     if (ModelMetadata.FromLambdaExpression(expression, html.ViewData).IsRequired)
     {
        label = new MvcHtmlString(label.ToString().Substring(0, label.ToString().Length - 8).Trim() +
            "<span style=\"color:red\" class=\"required-marker\">*</span></label>");
     }
     return label;
  }

private static MvcHtmlString BuildFormEntry(
      MvcHtmlString label, MvcHtmlString input, MvcHtmlString validation)
  {
     return new MvcHtmlString("<div class=\"editor-label\">" + label + "</div>\n" +
     "<div class=\"editor-field\">" + input + validation + "</div>\n\n");
     //return new MvcHtmlString("<div class=\"editor-label\">" + label + "</div>\n");
  }

方法调用与LabelFor:

一模一样
Html.EditorEntryFor(model => model.Project.FirstName)
//**equals to**
Html.LabelFor(model => model.Project.FirstName)

现在我希望 EditorEntryFor 中的表达式如下所示:

Html.EditorEntryFor(model => model.Project.FirstName, new { @title = "Enter firstname." })

然而,助手只接受一个参数表达式,我希望表达式值等于 model => model.Project.FirstName, new { @title = "Enter firstname." })

可是,Visual Studio总以为我输入第二个参数试试。 有没有办法强制表达式认为“,”是表达式的一部分而不是第二个参数?到目前为止,看起来正常字符串操作的 none 就可以解决问题 =(

先谢谢大家了!

除了已经提供的解决方案外,我还找到了一些非常有用的文章,它们极大地帮助了我实现我需要的东西:html helper with required fields, html helper