【问题标题】:How to customize the EditorFor CSS with razor如何使用 razor 自定义 EditorFor CSS
【发布时间】:2013-04-24 08:42:35
【问题描述】:

我有这门课

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>

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

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

    这是我的模型定义:

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

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

    通常你必须像这样在视图中使用EditorFor-Extension:

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

    问题:

    我不能在此处附加 CSS 类,因为我可以使用 Html.TextBoxFor 来做到这一点。

    使用EditorFor-Extension 提供自己的CSS 类(或其他HTML 属性,如tabindexreadonly)就是编写一个自定义HTML-Helper, 喜欢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 Html-Attribute 与我们自己的 CSS 类并附加其他额外的 HTML 属性。对于 HTML 解析,我使用 HtmlAgilityPack(使用 google)。

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

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

    使用此帮助器,您的货币价值应在视图中很好地显示。

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

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

    这是一个这样的模型绑定器的实现:

    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;
        }
    }
    

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

    protected void Application_Start()
    {
        ...
    
        ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
        ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
    
        ...
    }
    

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

    【讨论】:

      【解决方案2】:

      使用Views/Shared/EditorTemplates 中的自定义标记创建一个名为Contact.cshtml 的局部视图。这将覆盖默认编辑器。

      如@smartcavemen 所述,请参阅Brad Wilson's blog 了解模板简介。

      【讨论】:

      • +1,我还要提一下:Brad Wilson 的博客系列bradwilson.typepad.com/blog/2009/10/…
      • @smartcaveman 感谢您的链接,我不记得是谁写了那个系列。不知为何,我以为是 scottgu!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 2021-02-13
      • 2018-10-05
      相关资源
      最近更新 更多