【问题标题】:CustomAttribute reflects html attribute MVC5CustomAttribute 反映 html 属性 MVC5
【发布时间】:2014-10-23 00:43:34
【问题描述】:

希望找到一种方法,当在 MVC5 中自定义属性或更优选正则表达式属性装饰模型中的属性时,html 控件将包含它作为控件的另一个属性。例如

class CoolModel {
   [CustomHtmlAttribute("hello")]
   public string CoolValue {get;set;} 
}

输出...

<input type="text" customhtml="hello" />

或者类似的东西。所以对于 RegularExpressionAttribute,pattern 属性会很棒。

class CoolModel {
   [RegularExpressionAttribute("/d")]
   public string CoolValue {get;set;} 
}

输出...

<input type="text" pattern="/d" />

我需要这个输出而不启用 Javascript unobtrusive 选项。所以我正在考虑以一种方式在模型中指定一些属性,这些属性会被下推到视图中。不确定数据注释提供者是否可以完成这项工作。不确定是否可以扩展 Helper 以获得此结果。

感谢您的帮助。

【问题讨论】:

  • 要实现这一点,您只需使用标准助手并添加 html 属性 @Html.TextBoxFor(m =&gt; m.SomeProperty, new { customhtml = "hello" })。使用自定义数据注解会复杂得多
  • 感谢两位的回答。 @StephenMuecke 我知道,但出于可维护性目的,我需要在模型中指定属性。
  • @artm 我之前检查了该链接,我想知道是否有其他方法可以做到这一点。您能否添加一个元属性,无需执行整个过程即可在视图中呈现?
  • 在这种情况下,artm 的链接可能很有用,尽管它有点过时并且确实依赖于创建自定义 EditorTemplates,这可能难以跨项目维护。另一种选择是实现 IMetadataAware 以将属性添加到 metadata.AdditionalValues,然后创建一组自定义 html 帮助器来合并属性

标签: c# asp.net-mvc html asp.net-mvc-4 asp.net-mvc-5


【解决方案1】:

如果使用带有重载的标准帮助程序来添加 html 属性是不可接受的,那么您可以创建一个属性实现 IMetadataAware,将属性添加到 metadata.AdditionalValues,然后可以在自定义 html 帮助程序中使用。一个简单的例子可能是

[AttributeUsage(AttributeTargets.Property)]
public class CustomHtmlAttribute : Attribute, IMetadataAware
{
  public static string ValueKey
  {
    get { return "Value"; }
  }
  public string Value { get; set; }
  public void OnMetadataCreated(ModelMetadata metadata)
  {
    if (Value != null)
    {
      metadata.AdditionalValues[ValueKey] = Value;
    }
  }
}

并创建一个助手来渲染一个文本框(这里只显示一个重载)

public static MvcHtmlString CustomHtmlTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
  ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
  object attributes = null;
  if (metaData.AdditionalValues.ContainsKey(ValueKey))
  {
    attributes = new { customhtml = (string)metaData.AdditionalValues[ValueKey] };
  }
  return InputExtensions.TextBoxFor(helper, expression, attributes);
}

并将其用作

[CustomHtml(Value = "hello")]
public string CoolValue { get; set; } 

在视图中

@Html.CustomHtmlTextBoxFor(m => m.CoolValue)

为了使其更灵活一点,您可以向属性添加更多属性,以便将其应用为

[CustomHtml(Value = "hello", Pattern="/d")]
public string CoolValue { get; set; }

并修改帮助器以呈现您定义的所有 html 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多