ASP MVC Data Annotations and database null values

asp.net-mvc, data-annotations

Solution

You need to make the properties that you want to be optional of a NULLABLE type.

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

This way, the validator will not trigger... and if you think about it for a moment, it makes sense... the default value for an int is 0... but you actually want a NULL in your database.

Problem

I have a asp mvc 5 project and have created the database using code first and data migrations. This is my current product POCO class ``` 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; } } ``` In the database the only values that are not null, is the primary key and the name. I am having a problem with the Price, Category and Brand fields. In the form all 3 are still being "required" and the ModelState is not passing with jqueryval.js indicating that this values need to be added. As you can see in the image, the form will first show that the price & name values need to be added. Once i add those values and click "create". I am only then asked to add values for the brand and category. As indicated in the image below. It seems as if the brand and category and not being validated on the first click for some reason , but besides that these values should not have to be added as they are null values in the database , yet the model still requires that they be added. Just wondering if anyone has any insight to this. Is there maybe a data annotation i can add like ``` [Required(this = false)] ``` To overwrite this. And also How can i get Brand and category to be validated on the first submit click? Thanks.

Original source