Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

validation - ASP.NET MVC 4 avoid generation of data-val-date for datetime

how can I avoid the generation of the html attribute "data-val-date" for the element created from a Datetime property?

The model:

public class RegisterModel
{
    [Required]
    [Display(Name = "Date of birth")]
    public DateTime? DateOfBirth { get; set; }
}

The view:

@Html.LabelFor(m => m.DateOfBirth)
@Html.EditorFor(m => m.DateOfBirth)

In fact, I'm creating a three drop down lists element for selecting the date of birth, which don't give a value in a date format. Some solutions I've seen, consisted in a work around: removing the validation with a javascript. The solution I envisage is to split the DateTime property into three long one for each value (day, month, year).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ok, this took me an afternoon of work... apparently mvc4 decided that it was time to render a data-val-date="Message" on EVERY datetime property on the viewmodel. I've tried to modify this default behaviour but didn't succeed.

This solved my problems:

$.validator.addMethod('date',
    function (value, element) {
        return true; // since MVC4 data-val-date is put on EVERY vm date property. Default implementation does not allow for multiple cultures...
    });

You can also try to write your own editor template named "DateTime.cshtml" in your shared EditorFor folder, but don't use TextBoxFor there, because that one is polluted as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...