2
@using (Html.BeginForm("ForatExcel", "ForatSummary", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.DropDownList("ForatFrom", new SelectList(Model, "ID", "ID", new { onchange = "getAllData()" }))
@Html.DropDownList("ForatTo", new SelectList(Model, "ID", "ID", new { onchange = "getAllData()" }))
<br />
<input type="submit" id="btnForatVersion" value="Go"/> 
}

我需要验证“ForatFrom”下拉值是否大于“ForatTo”值。我想我不能使用模型验证,因为那只会检查下拉列表的值是否是一个特定的数字。我在想可能是 jquery 验证,但不确定最好的选择是什么?

谢谢

4

1 回答 1

1

您可以而且应该使用模型验证。我将实现一个验证属性 [LargerThan],如下所示:

public class LargerThanAttribute: ValidationAttribute, IClientValidatable
{
     private string _listPropertyName { get; set; }

     public LargerThanAttribute(string listPropertyName)
     {
         this._listPropertyName = listPropertyName;
     }

     protected override ValidationResult IsValid(object value, ValidationContext validationContext)
     {
        if(value == null)
            return new ValidationResult("Not a valid value");

        var listProperty = validationContext.ObjectInstance.GetType().GetProperty(_listPropertyName);
        double propValue = Convert.ToDouble(listProperty.GetValue(validationContext.ObjectInstance, null));

        if(propValue <= Convert.ToDouble(value))
            return ValidationResult.Success;

        return new ValidationResult("End value is smaller than start value");
    }
}

请注意,此代码未经测试,但如果您按照这一行编写一些内容并将其放在单独的类中,则可以在需要进行此类检查时重用它。您现在可以将其放在模型中的属性上

public double ForatFrom { get; set; }

[LargerThan("ForatFrom")]
public double ForatTo { get; set; }

现在您有了服务器模型验证,如果您愿意,现在可以实现 jQuery 非侵入式验证。在我看来,如果你需要验证,你至少应该在服务器上进行,如果你需要在客户端上进行,那么也可以在那里实现,但永远不要只依赖客户端验证。

这是一篇很好的文章,你可以阅读它,它会告诉你我刚刚做了什么,还解释了如何实现客户端验证:http ://thepursuitofalife.com/asp-net-mvc-3-unobtrusive-javascript-validation-with-custom -验证者/

于 2013-11-11T13:07:20.237 回答