gpt4 book ai didi

c# - CustomAttribute 反射(reflect) html 属性 MVC5

转载 作者:行者123 更新时间:2023-11-30 20:46:45 25 4
gpt4 key购买 nike

希望找到一种方法,当在 MVC5 中自定义属性或更好的 RegularExpressionAttribute 修饰模型中的属性时,html 控件将包含它作为控件的另一个属性。例如

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

输出...

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

或者类似的东西。因此,对于 RegularExpressionAttribute,模式属性将非常棒。

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

输出...

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

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

感谢您的帮助。

最佳答案

如果使用带有重载的标准帮助器来添加 html 属性是 Not Acceptable ,那么您可以创建一个属性实现 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; }

在 View 中

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

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

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

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

关于c# - CustomAttribute 反射(reflect) html 属性 MVC5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26519493/

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