【问题标题】:How to use RequiredIf with a property of GUID type?如何将 RequiredIf 与 GUID 类型的属性一起使用?
【发布时间】:2022-01-04 21:57:46
【问题描述】:

我有一个字符串类型的属性,称为地址。我有第二个 GUID 类型的属性,称为 ProjectTypeId。如果 ProjectTypeId 等于某个硬编码的 GUID 值,我想将 Address 属性设为必需。如何实施此解决方案?

我尝试了以下方法,但新 Guid("123-456-7890") 出现编译器错误 CS0182 错误:

    [MaxLength(10)]
    [TextInput(MaxLength = 10)]
    [Display(Name = "Address")]
    [RequiredIf("ProjectTypeId", new Guid("123-456-7890"), 
    ErrorMessage = "Address is required for Commercial Project Types.")]
    [StringLength(10, ErrorMessage = "The Address must be between 1 and 10 characters.", MinimumLength = 1)]
    public string Address { get; set; } 

注意:我在此示例中更改了实际的 GUID 值。实际的 GUID 值是其他值。

【问题讨论】:

  • RequiredIf属性是自己建的属性吗?如果是,请分享RequiredIfAttribute 课程。谢谢。
  • 公共类RequiredIfAttribute:ConditionalValidationAttribute {受保护的覆盖字符串ValidationName {get {返回“requiredif”; } } public RequiredIfAttribute(stringdependentProperty, object targetValue) : base(new RequiredAttribute(),dependentProperty, targetValue) { } protected override IDictionary GetExtraValidationParameters() { return new Dictionary { { "rule" , “必需的” } }; } }

标签: c# asp.net-mvc compiler-errors guid requiredfieldvalidator


【解决方案1】:

以下 URL 资源提供了我需要的解决方案:https://www.c-sharpcorner.com/article/dotvvm-build-conditional-validation-attribute/

我将代码更新为:

[RequiredIf("ProjectTypeId", "123-456-7890", ErrorMessage = "地址是...")]

注意:我在此示例中更改了实际的 GUID 值。实际的 GUID 值是其他值。

【讨论】:

    猜你喜欢
    • 2021-07-27
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多