Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //WebBootManager.cs:
- public override IBootManager Initialize()
- {
- //...
- // set metadata provider
- ModelMetadataProviders.Current = new DictionaryMetadataProvider();
- //...
- }
- //DictionaryMetadataProvider.cs:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Web.Mvc;
- using umbraco;
- using System.ComponentModel.DataAnnotations;
- namespace Umbraco.Web.Mvc
- {
- /// <summary>
- /// Model meta data provider that looks up display values and error messages from the Umbraco dictionary
- /// </summary>
- public class DictionaryMetadataProvider : DataAnnotationsModelMetadataProvider
- {
- protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
- {
- var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
- if (containerType != null && propertyName != null)
- {
- string dictKey = containerType.Name + "." + propertyName;
- metadata.DisplayName = LookupDictionaryValue(dictKey, metadata.DisplayName);
- metadata.NullDisplayText = LookupDictionaryValue(dictKey + ".NullDisplayText", metadata.NullDisplayText);
- foreach (var attribute in attributes)
- {
- if (attribute is ValidationAttribute)
- {
- string attributeName = attribute.GetType().Name;
- if (attributeName.EndsWith("Attribute"))
- attributeName = attributeName.Substring(0, attributeName.Length - 9);
- string attributeDictKey = containerType.Name + "." + propertyName + "." + attributeName;
- var validationAttribute = (ValidationAttribute)attribute;
- if (validationAttribute.ErrorMessageResourceName == null)
- {
- string errorMessage = LookupDictionaryValue(attributeDictKey, null);
- if (errorMessage != null)
- validationAttribute.ErrorMessage = errorMessage;
- }
- }
- }
- }
- return metadata;
- }
- /// <summary>
- /// Look up a value from the Umbraco dictionary
- /// </summary>
- /// <param name="dictKey">The dictionary item key</param>
- /// <param name="defaultValue">The default value to return if the dictionary item was not found</param>
- /// <returns>The dictionary item value, or defaultValue if item was not found in the dictionary</returns>
- protected virtual string LookupDictionaryValue(string dictKey, string defaultValue)
- {
- string dictValue = library.GetDictionaryItem(dictKey);
- return !string.IsNullOrEmpty(dictValue) ? dictValue : defaultValue;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement