简体   繁体   中英

Validation Summary using System.ComponentModel.DataAnnotations;

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>

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM