How to make a default editor template for enums?

前端 未结 7 1004
星月不相逢
星月不相逢 2020-12-08 03:11

How can I make a default editor template for enums? By which I mean: can I do something like this:

<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.V         


        
7条回答
  •  时光取名叫无心
    2020-12-08 03:40

    Late to answer but I hope this helps others. Ideally you want all enums to use your Enum template by convention, not by specifying a UIHint each time, and you can accomplish that by creating a custom model metadata provider like this:

    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    
    public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable attributes, Type containerType, Func modelAccessor, Type modelType, string propertyName) {
            var mm = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            if (modelType.IsEnum && mm.TemplateHint == null) {
                mm.TemplateHint = "Enum";
            }
            return mm;
        }
    }
    
    
    

    Then simply register it in the Application_Start method of Global.asax.cs:

    ModelMetadataProviders.Current = new CustomMetadataProvider();
    

    Now all your enum properties will use your Enum template by default.

    提交回复
    热议问题