ASP.NET MVC Editor-Templates/UIHint with parameters

前端 未结 2 1455
广开言路
广开言路 2020-12-23 00:11

I\'ve been using Editor-Templates in the past like this, by applying the following data annotation:

[UIHint("SomeTemplate")]
 

2条回答
  •  囚心锁ツ
    2020-12-23 00:28

    You could use the UHint without AdditionalMetadata attribute, but some additional code is requred

    [UIHint("DateTime", null, "key1", "value1", "key2", "value2")]
    public DateTime Date { get; set; }
    

    override CreateMetadata:

    public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
        {
            public const string UiHintControlParameters = "UiHintControlParameters";
    
            protected override ModelMetadata CreateMetadata(
                IEnumerable attributes,
                Type containerType,
                Func modelAccessor,
                Type modelType,
                string propertyName)
            {
    
                ModelMetadata metadata = base.CreateMetadata(
                    attributes,
                    containerType,
                    modelAccessor,
                    modelType,
                    propertyName);
    
                IEnumerable uiHintAttributes = attributes.OfType();
                UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => string.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase))
                                                  ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));
                if (uiHintAttribute != null)
                {
                    metadata.AdditionalValues.Add(UiHintControlParameters, uiHintAttribute.ControlParameters);
                }
    
                return metadata;
            }
    
    
    

    Register CustomMetadataProvider:

        public static void Application_Start()
        {
            ModelMetadataProviders.Current = new CustomMetadataProvider();
        }
    

    and in your template:

        @{
            IDictionary values = (IDictionary)
    ViewData.ModelMetadata.AdditionalValues[CustomMetadataProvider.UiHintControlParameters];
        }
    

    提交回复
    热议问题