1

ユーザーが選択リストから値を初めて選択すると、テキストPick oneと値を含むデフォルト オプションが表示されます-1

これを支援するために、カスタム属性がありますNotEqualAttribute。ドロップダウン リストが必要な場合は、正しく機能させるために両方の属性を使用する必要があります。

VM は次のようになります。

[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 の質問では、プロパティが明示的に設定されていない限り、null 非許容プロパティをオプション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