Mike Marks
Mike Marks

Reputation: 10139

ASP.NET MVC4 DataAnnotations Validation on Models acting very strange - validating all fields even when I only specify one field to be validated

To keep this real simple, I have a model that has just one Required attribute (just on the Name). My View only has one @Html.ValidationMessageFor that's tied to the Name. When I click Save on the View when nothing is filled in, all fields come back as required. If I fill in the Name field, the remaining fields come back as required. I really need some help figuring out why this is:

public class KeyActive
{
    [Key]
    public int Pk { get; set; }

    [Required(ErrorMessage="Name of filler is required.")]
    [Display(Name="Name:")]
    public string Name { get; set; }

    [Display(Name = "Capsule 00 Pack Stat:")]
    public int PackStat00 { get; set; }

    [Display(Name = "Capsule 0 Pack Stat:")]
    public int PackStat0 { get; set; }

    [Display(Name = "Capsule 1 Pack Stat:")]
    public int PackStat1 { get; set; }

    [Display(Name = "Capsule 3 Pack Stat:")]
    public int PackStat3 { get; set; }

    public string CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
}

Here's my View:

<div data-role="fieldcontain">
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>

<div data-role="fieldcontain">
    @Html.LabelFor(model => model.PackStat00)
    @Html.EditorFor(model => model.PackStat00)
</div>

<div data-role="fieldcontain">
    @Html.LabelFor(model => model.PackStat0)
    @Html.EditorFor(model => model.PackStat0)
</div>

<div data-role="fieldcontain">
    @Html.LabelFor(model => model.PackStat1)
    @Html.EditorFor(model => model.PackStat1)
</div>

<div data-role="fieldcontain">
    @Html.LabelFor(model => model.PackStat3)
    @Html.EditorFor(model => model.PackStat3)
</div>

Finally, when I fill out the form and click Save, here's what I get:

enter image description here

It's acting like every field is required- when I fill in Name, and leave everything else blank, it won't let me submit it because it seems to think the other fields are also required. I really need some help figuring out if there's another place that I'm not seeing that performs validation, or what I'm doing wrong here!! Thanks.

Upvotes: 1

Views: 1425

Answers (1)

CorrugatedAir
CorrugatedAir

Reputation: 819

Could it be because your ViewModel is using int instead of a nullable value:

public Nullable<int> PackStat00

or

public int? PackStat00

Right now, there's no way to store a null value in your view model for those fields.

Upvotes: 2

Related Questions