gpt4 book ai didi

c# - 使用 C# 的 ASP .NET MVC 3 自定义 Html 5 数据属性

转载 作者:行者123 更新时间:2023-11-28 02:07:08 29 4
gpt4 key购买 nike

我有以下问题。

我有 Html 元素,我想附加 Data- 属性和一个特定的类,就像这样:

<element id="" class="custom_class" data-attribute="value" data-attr-two="value2"></element>

但我想像这样在模型级别定义这些属性:

public class ModelName 
{
[DataAnnotation({attribute = "value", attr_2 = "value2"})]
[Class= "custom_class"]
public type PropertyName { get; set;}
}

我知道自定义验证属性,但问题是元素看起来像这样:

<element id="" class="custom_class" data-val-attribute="value"/></element>

不是这个:

<element id="" class="custom_class" data-attribute="value"/></element>

如果有另一种方法可以做到这一点,比如可以向 Html 助手添加另一个字典,如下所示:

@Html.TextBoxFor(model => Model, new { DataAnnotation : DataAnnotationObjectModel.Create({Message =        "something", Name = "something" }) )

DataAnnotationObject 将是一个类,其中包含正在使用的所有类型的数据属性和一些创建默认对象的方法,这些对象使用重复数据进行预枚举。

我知道我可以做到:

@Html.TextBoxFor(model => Model, new { data_attr = @item.Value }  )

但是我必须添加 5 个或更多属性,并且我要为每个模型中的每个属性添加 5 个或更多属性,并且我必须为每个属性至少添加 3 次。

有没有办法做到这一点?

如果您在理解这个问题时遇到问题,请随时发表评论并提出您的问题,我会尽力解释

最佳答案

作为快速解决方案,您可以尝试像这样定义 HTML Helper;

public static MvcHtmlString AttributedTextBoxFor<TModel, TProperty>(this HtmlHelper _helper, Expression<Func<TModel, TProperty>> expression)

在代码中,您应该能够检索从表达式中引用的属性(遵循 StackOverflow question ),并且通过使用反射,您应该能够再次获取该属性的属性 (PropertyInfo.Attributes)。一旦你有了这些,你应该能够生成一个匿名对象,其中定义了所有“data-”属性,并且从上面定义的帮助器返回标准 TextBoxFor 并传入这个对象:

return _helper.TextBoxFor(expression, myHtmlAttributes);

没有太多时间来编写完整的解决方案,但它应该只是几行样板代码。

关于c# - 使用 C# 的 ASP .NET MVC 3 自定义 Html 5 数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10775137/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com