CustomAttribute reflects html attribute MVC5

后端 未结 1 1933
自闭症患者
自闭症患者 2020-11-28 15:28

Hoping to find a way when in MVC5 a Custom attribute or preferable the RegularExpressionAttribute decorates a property in the model the html control will contain it as anoth

相关标签:
1条回答
  • 2020-11-28 16:14

    If using the standard helpers with the overload to add html attributes is not acceptable, then you can create an attribute implements IMetadataAware that adds properties to metadata.AdditionalValues which can then be used in custom html helpers. A simple example might be

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

    and to create a helper to render a textbox (only one overload shown here)

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

    and use it as

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

    and in the view

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

    to make this a bit more flexible, you could add more properties to the attribute so you could apply it as

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

    and modify the helper to render all the html attributes you define.

    0 讨论(0)
提交回复
热议问题