2012-05-09 102 views
0

我有一个简单的视图模型asp.net mvc3,为什么dataannotation验证没有验证器属性?

public class ProductViewModel 
{ 
    [Required(ErrorMessage = "This title field is required")] 
    public string Title { get; set; } 
    public double Price { get; set; } 
} 

这里是在此基础上视图模型我的形式。

@using (Html.BeginForm()) { 
@Html.ValidationSummary(true) 
<fieldset> 
    <legend>ProductViewModel</legend> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Title) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Title) 
     @Html.ValidationMessageFor(model => model.Title) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Price) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Price) 
     @Html.ValidationMessageFor(model => model.Price) 
    </div> 

    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 

}

我不想验证的价格领域。但它会自动验证,如果没有输入,将显示此字段是必需的。我注意到我使用双倍的价格。如果我将其更改为“字符串”。验证被删除。为什么键入“double”会导致自动验证?

回答

1

我不想验证价格字段。但它会自动验证,如果没有输入,将显示此字段是必需的

因为double是一个值类型,它不能为空。在模型double?:如果你想要的值,使不具有价值,使用nullable

public class ProductViewModel 
{ 
    [Required(ErrorMessage = "This title field is required")] 
    public string Title { get; set; } 
    public double? Price { get; set; } 
} 
+0

很好的答案,非常感谢。 – qinking126

1

因为双是值类型,并且不能为空。你可以做到这一点double?Nullable<double>,它会没事的。

+0

很好的答案,非常感谢。 – qinking126