简体   繁体   English

C#中的自定义属性可在html中提供自定义数据属性

[英]Custom Attribute in c# to give Custom data-attribute in html

I'd like to be able to make a data attribute in c# for an object in my model. 我希望能够在c#中为模型中的对象创建数据属性。 When this is displayed. 显示时。 I'd like the html to render the value in a data attribute within the html itself. 我希望html在html本身的data属性中呈现值。

In my head, the code looks similar to this. 在我看来,代码与此类似。

public class AffectsAttribute:Attribute
{
    public string[] Departments { get; set; }

}


[EmailAddress]
[Required(ErrorMessage = "Email is required")]
[Affects(Departments = new string[]{"Coaches"})]
public string Email {get; set;}

Then in the html, after being called with razor it would look something like this 然后在html中,用剃须刀调用后看起来像这样

@Html.EditorFor(model => model.Email)


<input class="text-box single-line" data-affects="Coaches" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="Email is required" id="Email" name="Email" type="email"  value="">

I have no clue how to specify that I would like the additional data attribute to be added when the item is rendered on a page. 我不知道如何指定要在页面上呈现项目时添加的其他数据属性。 Can anyone help? 有人可以帮忙吗?

It can be done through the ValidationAttribute . 可以通过ValidationAttribute完成。 If you inherit this: 如果您继承此:

public class MyCustomAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
    }
}

The GetClientValidationRules is what you are interested in. You return an IEnumerable of attributes you want the client to have. 您将对GetClientValidationRules感兴趣。您将返回一个IEnumerable属性,该属性是希望客户端具有的属性。

You can check out this article on CodeProject . 您可以在CodeProject上查看此文章。

You'll have to create a new HTML helper to do that. 您必须创建一个新的HTML助手来做到这一点。 http://www.asp.net/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs http://www.asp.net/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs

It's an extension from the HtmlHelper, that creates that. 它是HtmlHelper的扩展,可以创建该扩展。 Something like: 就像是:

  public static class YourExtensions
 {
      public static string YourMethodName(this HtmlHelper helper, string[] paramName)
      {
           return  String.Format("<input data-affects='{0}'>",String.Join(" ", paramName));
      }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM