ASP.NET MVC DataAnnotation必需1从3属性

时间:2018-10-09 20:29:16

标签: c# asp.net-mvc entity-framework data-annotations

我正在使用ASP.NET MVC创建一个项目。

我的模型类如下:

var expires = (new Date(Date.now() + 86400000)).toUTCString(); // 86400000 milliseconds is 24 hours
setCookie("splash", "1", expires, "/");

这里DECLARE @TableData as table ( DeliveryExtension nvarchar(260), ExtensionSettings xml ) INSERT INTO @TableData VALUES ('Report Server Email', '<ParameterValues><ParameterValue><Name>TO</Name><Value>name.one@companyinc.com; name.two@companyinc.com; name.3@companyinc.com</Value></ParameterValue><ParameterValue><Name>CC</Name><Value>name.four@companyinc.com; name.five@companyinc.com</Value></ParameterValue><ParameterValue><Name>IncludeReport</Name><Value>True</Value></ParameterValue><ParameterValue><Name>RenderFormat</Name><Value>EXCELOPENXML</Value></ParameterValue><ParameterValue><Name>Subject</Name><Value>@ReportName was executed at @ExecutionTime</Value></ParameterValue><ParameterValue><Name>Comment</Name><Value>Any undefined category is currently being addressed.</Value></ParameterValue><ParameterValue><Name>IncludeLink</Name><Value>False</Value></ParameterValue><ParameterValue><Name>Priority</Name><Value>NORMAL</Value></ParameterValue></ParameterValues>') ,('Report Server Email', '<ParameterValues><ParameterValue><Name>TO</Name><Value>name.one@companyinc.com; name.two@companyinc.com</Value></ParameterValue><ParameterValue><Name>CC</Name><Value>name.three@companyinc.com</Value></ParameterValue><ParameterValue><Name>IncludeReport</Name><Value>True</Value></ParameterValue><ParameterValue><Name>RenderFormat</Name><Value>EXCELOPENXML</Value></ParameterValue><ParameterValue><Name>Subject</Name><Value>@ReportName was executed at @ExecutionTime</Value></ParameterValue><ParameterValue><Name>Comment</Name><Value>@ReportName If there any issues with this report please open a ticket for Reporting Services Portal support.</Value></ParameterValue><ParameterValue><Name>IncludeLink</Name><Value>False</Value></ParameterValue><ParameterValue><Name>Priority</Name><Value>NORMAL</Value></ParameterValue></ParameterValues>') ,('Report Server FileShare', '<ParameterValues><ParameterValue><Name>PATH</Name><Value>\\network1234\c$\temp</Value></ParameterValue><ParameterValue><Name>FILENAME</Name><Value>AE Points Report</Value></ParameterValue><ParameterValue><Name>FILEEXTN</Name><Value>True</Value></ParameterValue><ParameterValue><Name>USERNAME</Name><Value>OCSgOkfVICihDFLe9g/oVGCa86jtJJLh2vqiuOYEvtYL1kudnJ6RuGqXlMpxqDz9</Value></ParameterValue><ParameterValue><Name>PASSWORD</Name><Value>f0zrUzblRan6Q9h9iW8FwevA9UKSo3guHz79rx3XG9i+OdAj3LxLaf659MJT0ZjE</Value></ParameterValue><ParameterValue><Name>RENDER_FORMAT</Name><Value>EXCELOPENXML</Value></ParameterValue><ParameterValue><Name>WRITEMODE</Name><Value>Overwrite</Value></ParameterValue><ParameterValue><Name>DEFAULTCREDENTIALS</Name><Value>False</Value></ParameterValue></ParameterValues>') select ExtensionSettings , ExtensionSettings.value(N'(/ParameterValues/ParameterValue[Name="TO"]/Value)[1]', 'varchar(250)') TO_, ExtensionSettings.value(N'(/ParameterValues/ParameterValue[Name="CC"]/Value)[1]', 'varchar(250)') CC, ExtensionSettings.value(N'(/ParameterValues/ParameterValue[Name="RenderFormat"]/Value)[1]', 'varchar(250)') RenderFormat from @TableData public class CaseInformation { public int Id { get; set; } public string CaseNumber { get; set; } public string RitNumber { get; set; } public string ApilNumber { get; set; } public DateTime Date { get; set; } public double CaseInvolvedRevenue { get; set; } public string CaseShortDescription { get; set; } public string CaseUpdateStatus { get; set; } public CompanyDetails CompanyDetails { get; set; } public int CompanyDetailsId { get; set; } } CaseNumber仅需要1。我不能将RitNumber放在所有这些对象上。我怎么做?请帮忙。

3 个答案:

答案 0 :(得分:2)

一种方法是,您可以实现自己的验证属性,如下所示-

public class CaseInfoRequiredAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var caseInfo = (CaseInformation) validationContext.ObjectInstance;
        if (string.IsNullOrEmpty(caseInfo.CaseNumber) &&
            string.IsNullOrEmpty(caseInfo.RitNumber) &&
            string.IsNullOrEmpty(caseInfo.ApilNumber))
        {
            return new ValidationResult("Either CaseNumber or RitNumber or ApilNumber is required.");
        }
        return ValidationResult.Success;        
    }
}

然后将自定义属性用于任何字段

public class CaseInformation
{
    public int Id { get; set; }

    [CaseInfoRequired]
    public string CaseNumber { get; set; }
    public string RitNumber { get; set; }
    public string ApilNumber { get; set; }

    public DateTime Date { get; set; }

    public double CaseInvolvedRevenue { get; set; }
    public string CaseShortDescription { get; set; }
    public string CaseUpdateStatus { get; set; }

    public CompanyDetails CompanyDetails { get; set; }
    public int CompanyDetailsId { get; set; }
}

答案 1 :(得分:2)

您可以在CaseInformation类本身中实现IValidatableObject接口。如下所示:

public class CaseInformation : IValidatableObject
{
    ...

    public IEnumerable<ValidationResult> Validate(ValidationContext ctx)
    {
        if (string.IsNullOrWhiteSpace(CaseNumber) &&
            string.IsNullOrWhiteSpace(RitNumber) &&
            string.IsNullOrWhiteSpace(ApilNumber))
        {
            yield return new ValidationResult("Your error message here.");
        }
    }
}

框架执行模型验证时会调用Validate(ValidationContext)方法。在这里,我们只是检查所有三个值是否都缺失,如果缺失,我们将通过返回带有自定义错误消息的ValidationResult来发出错误信号。

答案 2 :(得分:1)

您可以在模型中添加IsValid()函数,该函数返回true / false并将错误附加到ModelState。

CaseInformation:

public class CaseInformation
{
    public int Id { get; set; }

    public string CaseNumber { get; set; }
    public string RitNumber { get; set; }
    public string ApilNumber { get; set; }

    public DateTime Date { get; set; }

    public double CaseInvolvedRevenue { get; set; }
    public string CaseShortDescription { get; set; }
    public string CaseUpdateStatus { get; set; }

    public CompanyDetails CompanyDetails { get; set; }
    public int CompanyDetailsId { get; set; }

    public bool IsValid(out IDictionary<string, string> errors)
    {
        errors = new Dictionary<string, string>();
        if (string.IsNullOrWhiteSpace(CaseNumber) && string.IsNullOrWhiteSpace(RitNumber) &&
            string.IsNullOrWhiteSpace(ApilNumber))
        {
            errors.Add("MyError", "At least one Case, Rit or Apil number is required.");
        }
        return errors.Count == 0;
    }
}

然后在您的控制器中:

public ActionResult Index(CaseInformation model)
{
    if (!model.IsValid(out var errors))
    {
        foreach (KeyValuePair<string, string> error in errors)
        {
            ModelState.AddModelError(error.Key, error.Value);
        }                
    }
    if (ModelState.IsValid)
    {
        // it worked
    }
    else
    {
        // must be errors
    }
    return View();
}

然后在您看来:

@Html.ValidationSummary(false, "Please fix the below and try again.")