1

当用户第一次从选择列表中选择一个值时,我们会显示一个带有 textPick one和 value的默认选项-1

为了帮助解决这个问题,我们有一个自定义属性NotEqualAttribute。当需要下拉列表时,我们必须使用这两个属性才能使其正常工作。

我们的虚拟机看起来像:

[DisplayName("Pick Role")]  
[UIHint("DropDownList")]  
[Required]  
[NotEqual("-1", "Select value for DropDown")]  
public Int64 DdlSelected { get; set; }  
public List<DDLDispValueCV> DdlSelectedList { get; set; }  

我们更喜欢使用这个:

[DisplayName("Pick Role")]
[UIHint("DropDownList")]
[Required]
public Int64 DdlSelected { get; set; }
public List<DDLDispValueCV> DdlSelectedList { get; set; }

另一个 StackOverflow 问题讨论了如何使不可为空的属性变为可选,除非该Required属性被显式设置

我尝试这样做,但很困惑如何将新属性添加到IEnumerable<Attribute>集合和/或将其添加到ModelMetadata元数据提供程序中:

public class MyMetaDataProvider : 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);

        // Change how required is marked.
        // If required attribute found mark the IsRequired true, otherwise false.
        metadata.IsRequired = attributes.Where(x => x is RequiredAttribute).Count() > 0;

        // If working with a drop down.
        // And required attribute is present
        // Then add NotEqual attribute
        if ((metadata.TemplateHint != null) && (metadata.TemplateHint.ToString() == "DropDownList"))
        {
            // only add attribue if required.
            if (metadata.IsRequired)
            {
                // Add custom attribute NotEqual.
                NotEqualAttribute newAttr = new NotEqualAttribute("-1", "(Pick One) is not valid selection");
                IEnumerable<Attribute> newAttrs = attributes.Concat(new[] {newAttr});
                metadata = base.CreateMetadata(newAttrs, containerType, modelAccessor, modelType, propertyName);
                metadata.IsRequired = true;
            }
        }
     }  
}
4

0 回答 0