我有这样的模型验证只适用于字符串
模型类:
public class Circle
{
[Required(ErrorMessage = "Diameter is required")]
public int Diameter { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Color { get; set; }
}
测试:
[TestMethod]
public void TestCircle()
{
Circle circle = new Circle();
circle.Diameter = 5;
circle.Color = "Black";
ValidationContext contex = new ValidationContext(circle, null, null);
Validator.ValidateObject(circle , contex);
}
我期待它会失败,只要直径或者颜色为空。但是,上述测试仅在字符串参数Color为空时失败。为什么?我应该怎么做才能验证Diameter?
我猜猜它是因为int不可为空并且默认为0,因此在这种情况下有效。不完全确定。如果在你的圈子类中使用int(nullable int),会发生什么? – hschne 2014-09-10 14:30:35
'int'默认为0,如果你想测试'null'你必须使用'int?'。此外,我认为你想写'circle.Diameter'而不是'Circle.Diameter',因为'Diameter'不是'静态的' – glautrou 2014-09-10 14:48:58
这很有道理,谢谢大家! – ydoow 2014-09-10 14:59:28