MVC3-在html.helper中获取数据属性 [英] MVC3 - Get Data Attribute in html.helper
问题描述
我正在尝试创建一个自定义属性,以控制自定义HTML帮助器对象中的格式。我的自定义选择器类的源代码为(代码来自 http:// forums。 asp.net/t/1649193.aspx/1/10 )。
I'm trying to create a custom attribute to control formatting in a custom HTML helper object. The source code for my custom selector class is (Code is from http://forums.asp.net/t/1649193.aspx/1/10).
public static MvcHtmlString DdUovFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var m = expression.Body.GetType();
IDictionary<string, object> validationAttributes = htmlHelper
.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);
if (htmlAttributes == null)
htmlAttributes = validationAttributes;
else
htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value);
return SelectExtensions.DropDownListFor(htmlHelper, expression,
selectList, optionLabel, htmlAttributes);
}
我的自定义属性是
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property |
AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class LookUpAttribute : Attribute
{
public LookUpAttribute(Type providerName)
{
this.providerName = providerName;
}
protected ILookup providerName;
}
我的问题是我无法弄清楚如何在HTML帮助程序方法。
My problem is that I cannot figure out how to retrieve my custom attribute in in the HTML helper method.
推荐答案
实现此目标的最佳方法是让您的属性实现 IMetadataAware
。在 OnMetadataCreated
方法的实现中,应将值添加到 metadata.AdditionalValues
字典中。然后,您可以在帮助器中或任何其他可以访问ModelMetadata的地方检索值。
The best way to achieve this is for your attribute to implement IMetadataAware
. In the implementation of the OnMetadataCreated
method you should add values to the metadata.AdditionalValues
dictionary. You can then retrieve the value in your helper or wherever else you have access to ModelMetadata.
请注意,此解决方案是首选的,因为它实际上并未编码有关事实的任何信息您的元数据由属性驱动。
Note that this solution is prefered because it does not actually encode any information about the fact that your metadata is driven by attributes.
这篇关于MVC3-在html.helper中获取数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!