MVC模型中的自定义验证

时间:2016-03-26 05:03:49

标签: asp.net-mvc-4

我的模特是

public class GroupedIssueData
{

    [Range(0, double.MaxValue, ErrorMessage = "Please enter valid number")]
    public double IssueQty { get; set; }

    public double ReqQty { get; set; }

    public bool isSavings { get; set; }
}

这包含两个属性IssueQty和IsSaving,如果选中IsSaving,则IssueQty可以为空,如果IssueQty不为空,则IsSaving可以留空。我该如何验证

我的观点是

<td>
    @Html.DisplayFor(m => m.MaterialData[i].ReqQty)
    @Html.HiddenFor(m => m.MaterialData[i].ReqQty)
</td>
<td>@Html.TextBoxFor(m => m.MaterialData[i].IssueQty, new { style = "width:70px" })@Html.ValidationMessageFor(m => m.MaterialData[i].IssueQty)</td>
<td class="text-center">@Html.CheckBoxFor(m => m.MaterialData[i].isSavings)</td>

我的控制器是

public async Task<ActionResult> GetWorkOrderMaterialDetails(IssueEntryModel m)
{
    if (!ModelState.IsValid)
    {
        // redirect
    }
    var model = new IssueEntryModel();
}

如果模型无效,我该如何重定向到。我是否需要重定向到同一个控制器。我想保留输入的数据。

我的观点是

3 个答案:

答案 0 :(得分:0)

试试这个

`

 [Required]  
        [Range(18, 100, ErrorMessage = "Please enter an age between 18 and 50")]  
        public int Age { get; set; }  


    [Required]         
    [StringLength(10)]  
    public int Mobile { get; set; }            

    [Range(typeof(decimal), "0.00", "15000.00")]  
    public decimal Total { get; set; }  `

 if (ModelState.IsValid)  
        {  
            //
        }  
        return View(model);  

Validation to the Model

Custom Validation Data Annotation Attribute

答案 1 :(得分:0)

您可以进行自定义验证,例如RequiredIfOtherFieldIsNullAttribute如下所述:

How to validate one field related to another's value in ASP .NET MVC 3

public class RequiredIfOtherFieldIsNullAttribute : ValidationAttribute,      IClientValidatable
{
private readonly string _otherProperty;
public RequiredIfOtherFieldIsNullAttribute(string otherProperty)
{
    _otherProperty = otherProperty;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var property = validationContext.ObjectType.GetProperty(_otherProperty);
    if (property == null)
    {
        return new ValidationResult(string.Format(
            CultureInfo.CurrentCulture, 
            "Unknown property {0}", 
            new[] { _otherProperty }
        ));
    }
    var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);

    if (otherPropertyValue == null || otherPropertyValue as string == string.Empty)
    {
        if (value == null || value as string == string.Empty)
        {
            return new ValidationResult(string.Format(
                CultureInfo.CurrentCulture,
                FormatErrorMessage(validationContext.DisplayName),
                new[] { _otherProperty }
            ));
        }
    }

    return null;
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
        ValidationType = "requiredif",
    };
    rule.ValidationParameters.Add("other", _otherProperty);
    yield return rule;
}

}

并使用它:

[RequiredIfOtherFieldIsNull("IsSavings")]
public double IssueQty { get; set; }
[RequiredIfOtherFieldIsNull("IssueQty")]
public bool IsSavings { get; set; }

答案 2 :(得分:0)

使用obj exporter

但是你的情况:如果选中了IsSaving,那么IssueQty可以为空,如果IssueQty不为空,那么IsSaving可以留空有点混乱,但这可能暗示你

public class GroupedIssueData : IValidatableObject
{
    [Range(0, double.MaxValue, ErrorMessage = "Please enter valid number")]
    public double IssueQty { get; set; }

    public double ReqQty { get; set; }

    public bool isSavings { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (!isSavings && IssueQty == 0)
        {
            yield return new ValidationResult("Error Message");
        }
    }
}

public async Task<ActionResult> GetWorkOrderMaterialDetails(IssueEntryModel m)
{
    if (!ModelState.IsValid)
    {
        return View(m);
        // redirect
    }

}