Tuesday, June 21, 2011

Non-validation on DateTime and other primitive types on ASP.NET MVC

Even you don't have any Required attribute on a value type property, i.e. primitive types and struct; ASP.NET MVC validation will still kick-in. You must make the field nullable

public class SalesFilterViewModel
{
    public int CompanyId { get; set; } // will be required, even there's no Required attribute
    public int? BranchId { get; set; } // will not be required
    
    public DateTime? StartingDate { get; set; } // nullable, will not be required
    public DateTime? EndDate { get; set; } // nullable, will not be required
}

// A true-false type of polling
public class Poll
{        
    public string QuestionId { get; set; }

    // When a default value of false(when you don't make the bool nullable, 
    // it will default to false on page load) doesn't make sense, 
    // but an answer(either true or false) is still required, make the 
    // property nullable and add a Required attribute.
    [Required]
    public bool? YourAnswer { get; set; }
}

No comments:

Post a Comment