css - 如何使用 razor 自定义 EditorFor CSS

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

我有这门课

public class Contact
{
    public int Id { get; set; }
    public string ContaSurname { get; set; }
    public string ContaFirstname { get; set; }
    // and other properties...
}

我想创建一个允许我编辑所有这些字段的表单。所以我用了这段代码

<h2>Contact Record</h2>

@Html.EditorFor(c => Model.Contact)

这很好用,但我想自定义元素的显示方式。例如,我希望每个字段与其标签显示在同一行中。因为现在,生成的 html 是这样的:

<div class="editor-label">
  <label for="Contact_ContaId">ContaId</label>
</div>
<div class="editor-field">
  <input id="Contact_ContaId" class="text-box single-line" type="text" value="108" name="Contact.ContaId">
</div>

最佳答案

同意上面jrummell的解决方案: 当您使用 EditorFor-Extension 时,您必须编写自定义 描述可视组件的编辑器模板。

在某些情况下,我觉得使用编辑器模板有点生硬 具有相同数据类型的多个模型属性。在我的例子中,我想在我的模型中使用十进制货币值,它应该显示为格式化字符串。我想在我的 View 中使用相应的 CSS 类来设置这些属性的样式。

我见过其他实现,其中 HTML 参数已使用模型中的注释附加到属性。我认为这很糟糕,因为 View 信息(如 CSS 定义)应该在 View 中设置,而不是在数据模型中设置。

因此我正在研究另一种解决方案:

我的模型包含一个 decimal? 属性,我想将其用作货币字段。 问题是,我想在模型中使用数据类型 decimal?,但是显示 View 中的十进制值作为使用格式掩码的格式化字符串(例如“42,13 €”)。

这是我的模型定义:

[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal? Price { get; set; }

格式掩码 0:C2decimal 格式化为小数点后两位。 ApplyFormatInEditMode 很重要, 如果您想使用此属性来填充 View 中的可编辑文本字段。所以我将它设置为 true,因为在我的例子中我想将它放入一个文本字段中。

通常您必须像这样在 View 中使用 EditorFor-Extension:

<%: Html.EditorFor(x => x.Price) %>

问题:

我不能在此处附加 CSS 类,因为我可以使用 Html.TextBoxFor 来完成。

通过 EditorFor-Extension 提供自己的 CSS 类(或其他 HTML 属性,如 tabindexreadonly)是编写一个自定义 HTML 助手, 像 Html.CurrencyEditorFor。这是实现:

public static MvcHtmlString CurrencyEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Object htmlAttributes)
{
  TagBuilder tb = new TagBuilder("input");

  // We invoke the original EditorFor-Helper
  MvcHtmlString baseHtml = EditorExtensions.EditorFor<TModel, TValue>(html, expression);

  // Parse the HTML base string, to refurbish the CSS classes
  string basestring = baseHtml.ToHtmlString();

  HtmlDocument document = new HtmlDocument();
  document.LoadHtml(basestring);
  HtmlAttributeCollection originalAttributes = document.DocumentNode.FirstChild.Attributes;

  foreach(HtmlAttribute attr in originalAttributes) {
    if(attr.Name != "class") {
      tb.MergeAttribute(attr.Name, attr.Value);
    }
  }

  // Add the HTML attributes and CSS class from the View
  IDictionary<string, object> additionalAttributes = (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

  foreach(KeyValuePair<string, object> attribute in additionalAttributes) {
    if(attribute.Key == "class") {
      tb.AddCssClass(attribute.Value.ToString());
    } else {
      tb.MergeAttribute(attribute.Key, attribute.Value.ToString());
    }
  }

  return MvcHtmlString.Create(HttpUtility.HtmlDecode(tb.ToString(TagRenderMode.SelfClosing)));
}

想法是使用原始的 EditorFor-Extension 来生成 HTML 代码并解析此 HTML 输出字符串以替换创建的 具有我们自己的 CSS 类的 CSS Html-Attribute 并附加其他额外的 HTML 属性。对于 HTML 解析,我使用 HtmlAgilityPack(使用谷歌)。

在 View 中,您可以像这样使用这个助手(不要忘记将相应的命名空间放入 View 目录中的 web.config 中!):

<%: Html.CurrencyEditorFor(x => x.Price, new { @class = "mypricestyles", @readonly = "readonly", @tabindex = "-1" }) %>

使用这个助手,您的货币值应该在 View 中很好地显示。

如果你想发布你的 View (表单),那么通常所有的模型属性都会被发送到你的 Controller 的操作方法。 在我们的例子中,将提交一个字符串格式的十进制值,该值将由 ASP.NET MVC 内部模型绑定(bind)类处理。

因为此模型绑定(bind)器需要一个 decimal? 值,但得到一个字符串格式的值,所以将抛出异常。所以我们必须 将格式化的字符串转换回它的 decimal? - 表示。因此,一个自己的 ModelBinder 实现是必要的, 将货币小数值转换回默认小数值(“42,13 €”=>“42.13”)。

下面是这种模型绑定(bind)器的实现:

public class DecimalModelBinder : IModelBinder
{

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      object o = null;
      decimal value;

      var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
      var modelState = new ModelState { Value = valueResult };

      try {

        if(bindingContext.ModelMetadata.DataTypeName == DataType.Currency.ToString()) {
          if(decimal.TryParse(valueResult.AttemptedValue, NumberStyles.Currency, null, out value)) {
            o = value;
          }
        } else {
          o = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
        }

      } catch(FormatException e) {
        modelState.Errors.Add(e);
      }

      bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
      return o;
    }
}

Binder 必须在您的应用程序的 global.asax 文件中注册:

protected void Application_Start()
{
    ...

    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

    ...
}

也许解决方案会对某人有所帮助。

关于css - 如何使用 razor 自定义 EditorFor CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12675708/

相关文章:

c# - 编辑 Resources.resx 文件时,Resources.Designer.cs 无法更新,因为 TFS 未将其 checkout

html - 我想将第一列设为静态并使其可排序?

css - 像代码一样编辑 facebook 页面

asp.net-mvc-3 - DTO 可以嵌套 DTO 吗?

c# - 使用 ASP.Net MVC3 显示 byte[] 中包含的图像

css - 使用 Razor 将样式编程盟友添加到垂直导航菜单的问题

javascript - 使用 jquery 保存 contenteditable 数据

css - 在 CSS 中选择动态元素名称

c# - ASP.NET MVC3 : Confirmation Box before submitting

javascript - $ae。 JavaScript 表示法