0

I have a ViewModel with some random properties...

public class TestViewModel
{
    [Required]
    [MaxLength(255)]
    [Display(Name = "Test Name (1.B.1)")]
    public string Name { get; set; }

    [DataType("Date")]
    [Display(Name = "Date Created")]
    public DateTime DateCreated { get; set; }

    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string ZIP { get; set; }

    [Display(Name = "City")]
    public int CityID { get; set; }

    [Display(Name = "Country")]
    public int CountryID { get; set; }

    [Display(Name = "State")]
    public int StateID { get; set; }
}

Not once have I declared that the CityID, StateID or CountryID are required values (which they aren't) and yet in my controller on ModelState.IsValid it fails the check and in the ValidationMessageFor it responds with City field is required.

Why does it think this? when Address1 and Address2 do not throw such required notices?

This is what one of the form fields look like:

    <div class="form-group">
        @Html.LabelFor(model => model.CountryID, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.CountryID, new { @class = "text-box single-line countries typeahead" })
            @Html.ValidationMessageFor(model => model.CountryID)
        </div>
    </div>
Charles
  • 50,943
  • 13
  • 104
  • 142
Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233

1 Answers1

0

CityID, CountryID and StateID are Required because they are int.

To make them optional, make them Nullable<int>

You can remove that behavior like this: source

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
Community
  • 1
  • 1
Alexandre Rondeau
  • 2,667
  • 24
  • 31
  • I'm sure it's there, somewhere really deep in the MSDN documentation. All non-nullable Value types are required by default. – Alexandre Rondeau Mar 04 '14 at 17:55
  • Cool man... thanks so much... I thought it was being clever and looking in my database against an entity and realising it was NOT NULL... but hey.. haha – Jimmyt1988 Mar 04 '14 at 17:57
  • @AlexandreRondeau The reason is any value types can't be empty. If your database has a nullable int and your model doesn't, your model will always have a value (0 for int) regardless of your setting of the property. A nullable value type closely model a nullable column in a database. This is also an issue for `RequiredAttribute` on value types. – Simon Belanger Mar 04 '14 at 18:14