ASP MVC数据注释和数据库空值

时间:2014-02-25 12:00:27

标签: asp.net-mvc data-annotations

我有一个asp mvc 5项目,并且首先使用代码和数据迁移创建了数据库。

这是我目前的产品POCO类

public class Product
{
    [Key]
    public int ProductId { get; set; }

    [Required(ErrorMessage = "Please add a product name.")]
    [StringLength(50)]
    public string Name { get; set; }
    public string Code { get; set; }

    [DataType(DataType.MultilineText)]
    public string Description { get; set; }
    public string Features { get; set; }
    public decimal Price { get; set; }
    public bool? Promotion { get; set; }

    [Display(Name = "Category")]
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }

    [Display(Name = "Brand")]
    public int BrandId { get; set; }
    public virtual Brand Brand { get; set; }

    public byte[] ImageData { get; set; }

    [HiddenInput(DisplayValue = false)]
    public string ImageMimeType { get; set; }
}

在数据库中,唯一不为null的值是主键和名称。我的价格类别品牌字段存在问题。在表单中,所有3个仍然是“required”,并且ModelState没有使用jqueryval.js传递,表明需要添加此值。

enter image description here

正如您在图片中看到的那样,表单将首先显示价格&需要添加名称值。一旦我添加了这些值并单击“创建”。然后我才被要求为品牌和类别添加值。如下图所示。

enter image description here

似乎品牌和类别并没有因为某些原因在第一次点击时被验证,但除了这些值不应该被添加,因为它们是数据库中的空值,但模型仍然需要它们加上。只是想知道是否有人对此有任何见解。是否可以添加数据注释,如

[Required(this = false)]

要覆盖此内容。

此外,我如何才能在第一次提交点击时验证品牌和类别?

感谢。

2 个答案:

答案 0 :(得分:9)

您需要使您想要选择NULLABLE类型的属性。

public decimal? Price { get; set; }
public int? CategoryId { get; set; }
public int? BrandId { get; set; }

这样,验证器不会触发......如果你想一下它,它是有意义的...... int的默认值是0 ......但你实际上想要数据库中的NULL

答案 1 :(得分:1)

要允许空字符串,只需添加那些注释

[DisplayFormat(ConvertEmptyStringToNull = false)]
[Required(AllowEmptyStrings =true)]