简体   繁体   中英

Model attribute validation issue

I am formatting DateTime? field like dd/MM/yyyy and when I submit form it shows validation error.

在此处输入图片说明

I cannot get it why is it happens?

Model

[Display(Name = "Expected Ending Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? ExpectedEndingTime { get; set; }

HTML

@Html.TextBoxFor(x => x.Requsition.ExpectedEndingTime, new { @class = "form-control dataPickerField", id = "ExpectedEndingTimeDataPicker", @readonly = true })

@Html.ValidationMessageFor(x => x.Requsition.ExpectedEndingTime)



<script>
    $(function () {            
        $('#ExpectedEndingTimeDataPicker').datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true           
        })
        .on('changeDate', function (ev) {
              //  do things;
    );
    });
</script>

I think that DataFormatString is used just for displaying, and it doesn't use by ModelBinder for parsing. So your server still uses Culture from web.config.

You can hardcode specific culture in config that should be used with this date format.

Here is an answer that can help you - https://stackoverflow.com/a/8035636/169635 It has a sample of IModelBinder that uses CurrentCulture for parsing. You can specify own format

Nothing was useful for me guys....

So I added 1 extra field to the Model and will keep DateTime like a String in the format I need.

And for places I need DateTime format I have another field.

[Display(Name = "Expected Ending Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? ExpectedEndingTime { get; set; }


[Required]
[Display(Name = "Expected Ending Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public string ExpectedEndingTimeAsString { get; set; }  

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