ASP.Net MVC C# Chrome not showing date in edit mod

2019-06-15 07:31发布

问题:

I am using Google Chrome V28 as my browser - and have a problem with the DataAnnotations on my model, which force Chrome to use it's own inbuild calendar when rendering a datatime type in my view.

My model is:

public class ObScore
{
    public int ObScoreId { get; set; }

    ...
    ...
    [DisplayFormat(DataFormatString = "{0:dd MMMM yyyy}", ApplyFormatInEditMode = true)]
    [Display(Name = "Date")]
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }
    ...
    ...
}

There is definitely data in the model:

...but when displaying in Edit mode, Chrome shows:

Is this a known bug in Chrome, and is there anything I can do in my code, to force the date into the form?

Thanks, Mark

回答1:

Try removing [DataType(DataType.Date)] because I believe this creates <input type="date" />. If you do that you'll end up with a <input type="text" /> to which you can attach jQuery date-picker.

Try w3schools: input type date in different browsers to see the difference.

Edit:

In the past I used the following in my View to make this work with jQuery date-picker (if you're interested in using it).

@Html.TextBoxFor(model => model.DateOfBirth, @"{0:yyyy\/MM\/dd}", new { @class = "datepicker" })



回答2:

Sorry to resurrect a 6 month old question, but I was having the same problem and have an answer that I feel is exactly what the OP was looking for.

While answer from mikhairu does work, it requires changing the type to text. The screenshots by the OP show Chrome's inbuilt datepicker UI, which requires the input to be type=date. Chrome requires the value of an input type=date to be in the format of YYYY-MM-DD, presumably to avoid any culture-specific ambiguity.

Therefore, in your model, add this data annotation to your date properties:

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]


回答3:

To display the date using the default chrome datepicker you need two attributes on your model:

  • [DataType(DataType.Date)] results in <input type="date" />. See this answer.
  • [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]. The format yyyy-MM-dd is required for the chrome date picker. See this answer.

For example:

Model

public class ObScore
{
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime Date { get; set; }
}

Razor View

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

        @* Control with date picker *@
        @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
    </div>
</div>


回答4:

I’ve been struggling with this issue while developing an MVC application in Asp.Net Core 2.0. There really doesn’t seem to be a complete perfect solution for all browsers.

The solution provided by erdinger above does not address the issue for someone using the asp-for= attribute in an Asp.Net Core 2.0 application. Furthermore, if you are using Entity Framework to generate migrations to the database, removing the [DataType(DataType.Date)] attribute in the model will result in the datatype in your database table being created (or changed) to a text type when you may in fact require a date type in your database table. I would suggest leaving the [DataType(DataType.Date)] attribute alone.

As I said above, there is no perfect solution for all browsers. So, what I did was to compromise slightly by not requiring an exact format for the edit form while still keeping my special format for all other displays of the date.

Here is the DateCompleted part of my model:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}", ApplyFormatInEditMode = false)]
[Display(Name = "Date Completed")]
public DateTime DateCompleted { get; set; }

As you might notice, the main thing I changed is the bool value in the [DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}", ApplyFormatInEditMode = false)] attribute.

I set it to false instead of true. You might also get the same results by eliminating the ApplyFormatInEditMode part altogether.

such as: [DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]

The view code in razor syntax looks like this:

<div class="form-group">
    <label asp-for="DateCompleted" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="DateCompleted" class="form-control" />
        <span asp-validation-for="DateCompleted" class="text-danger"></span>
    </div>
</div>

Given a date of January 26th 2016, the format for non-form input objects shows as Jan 26, 2016. However, the results in the edit form, although not exactly perfect render the date in Firefox and Internet Explorer as 2016-01-26. In Chrome and Edge, the result displays 1/26/2016 and allows these browsers’ built-in calendar popups to work flawlessly.

The good thing is that all these browsers display the desired date format in non-form input situations and still at least display a date in the form fields instead of displaying dd/mm/yyyy.

I hope this helps.



回答5:

I had the same problem but working with MVC5. You can try the jQuery UI Date Picker. This tutorial can help. Below, the essential parts.

  1. Install the jQuery.UI.Combined via NuGet, this will add the needed css and js files to your project.
  2. Include the added css and js files in the App_Start\BundleConfig.cs

    bundles.Add(new ScriptBundle("~/bundles/jqueryui")
           .Include("~/Scripts/jquery-ui-{version}.js"));
    bundles.Add(new StyleBundle("~/Content/jqueryui")
           .Include("~/Content/themes/base/all.css"));
  3. Reference the required files in views by updating the _Layout.cshtml. At the top of this file add:

    @Styles.Render("~/Content/jqueryui")

At its bottom add:

@Scripts.Render("~/bundles/jqueryui")
<script>
    $(function () {
        $(".jqueryui-marker-datepicker").datepicker({
            dateFormat: "yy-mm-dd",
            changeYear: true,
            showOn: "button"
        }).css("display", "inline-block").next("button").button({
            icons: { primary: "ui-icon-calendar" },
            label: "Select a date",
            text: false
        });
    });
</script>
  1. Add an editor template Views\Shared\EditorTemplates\Date.cshtml with the following code:
@model DateTime?
@Html.TextBoxFor(model => Model,
   "{0:dd-MM-yyyy}",
   new { @class = "form-control
   jqueryui-marker-datepicker" })

Your date field will now have a date picker with the correct date shown in the Edit mode.