Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Displaying DateTime picker instead of Date picker in ASP .NET MVC 5.1/HTML 5 specific

I write application in ASP .NET MVC 5.1

I have a field:

  [DisplayName("Date of Birth")]
  [DataType(DataType.Date)]
  public DateTime BirthDate { get; set; }

and then in View

  <div class="form-group">
            @Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BirthDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
            </div>
        </div>

which translates to:

enter image description here

if I just change annotiations above property in model to:

    [DisplayName("Date of Birth")]
    [DataType(DataType.DateTime)]

I don't get any picker displayed. If I change them to:

 [DisplayName("Date of Birth")]
 [DataType(DataType.Time)]

there is only hh:mm to choose from.

Question: Displaying DateTime picker instead of Date picker in ASP .NET MVC 5.1. I am asking for ASP .NET 5.1 HTML 5 specific solution.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your requirements are pretty picky...

Specifying the attribute Datatype for a field, will generate an input having as type the attribute specified. That's why when you add [DataType(DataType.Date)], the input generated will be a date picker, but if you add [DataType(DataType.DateTime)], the input will be of type datetime, thus why you don't get any picker displayed. Why? Because a few years ago, the browsers supporting input datetime decided to stop supporting it and W3C removed this feature due to lack of implementation.

However, not so long ago, some browser vendors started supporting again datetime-local which is back on the draft. As of now, the latest versions of Chrome, Opera and Microsoft Edge support it.

One solution would be to use the BootStrap or the jQuery Datetime Picker as Ajay Kumar suggested.

Another one would be, if you don't mind the few supporting browsers, to use datetime-local. Like this for instance:

@Html.TextBoxFor(model => model.BirthDate, new { type = "datetime-local"})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...