web-dev-qa-db-ja.com

MVC4 DataType.Date EditorはChromeでは日付を表示しませんが、Internet Explorerでは問題ありません。

モデルにDataType.Date属性を、ビューにEditorForを使用しています。これは Internet Explorer 8 および Internet Explorer 9 では問題なく機能していますが、 Google Chrome では日付ピッカーが表示され、値は表示されませんそれは単に「月/日/年」を薄い灰色のテキストで表示します。

Google Chromeに値が表示されないのはなぜですか。

モデル:

[DataType(DataType.Date)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }

見る:

<td class="fieldLabel">Est. Pur. Date</td>
<td class="field">@Html.EditorFor(m=>m.EstPurchaseDate)</td>

Chrome

Internet Explorer

195
Ben Finkel

モデルプロパティを[DataType(DataType.Date)]で装飾すると、ASP.NET MVC 4のデフォルトテンプレートはtype="date"の入力フィールドを生成します。

<input class="text-box single-line" 
       data-val="true" 
       data-val-date="The field EstPurchaseDate must be a date."
       id="EstPurchaseDate" 
       name="EstPurchaseDate" 
       type="date" value="9/28/2012" />

Google ChromeなどのHTML 5をサポートするブラウザは、日付入力を使ってこの入力フィールドをレンダリングします。

日付を正しく表示するには、値を2012-09-28の形式にする必要があります。 仕様 からの引用

value:[RFC 3339]で定義されている有効な満期日。年の構成要素は4以上の数字であるという追加の資格を持ちます。 0よりも大きい。

DisplayFormat属性を使用してこのフォーマットを強制することができます。

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }
371
Darin Dimitrov

MVC 5.2では、フォルダ〜/ Views/Shared/EditorTemplatesにDate.cshtmlを追加します。

@model DateTime?
@{
    IDictionary<string, object> htmlAttributes;
    object objAttributes;
    if (ViewData.TryGetValue("htmlAttributes", out objAttributes))
    {
        htmlAttributes = objAttributes as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(objAttributes);
    }
    else
    {
        htmlAttributes = new RouteValueDictionary();
    }
    htmlAttributes.Add("type", "date");
    String format = (Request.UserAgent != null && Request.UserAgent.Contains("Chrome")) ? "{0:yyyy-MM-dd}" : "{0:d}";
    @Html.TextBox("", Model, format, htmlAttributes)
}
41
Charlie

Darin Dimitrovの答えに加えて:

この特定の行に特定の(標準とは異なる)形式だけを使用したい場合は、MVC5で使用できます。

@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })
16
Arjan

MVC 3では、私は追加しなければなりませんでした:

using System.ComponentModel.DataAnnotations;

プロパティを追加するときの使い方

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

特にあなたが私のように.edmxファイルでこれらのプロパティを追加しているならば。デフォルトでは.edmxファイルはこれを使っていないので、プロパティだけを追加するだけでは不十分であることがわかりました。

11
Azoro

モデルから[DataType(DataType.Date)]を削除すると、Chromeの入力フィールドはtype="datetime"としてレンダリングされ、日付ピッカーも表示されません。

10
bernieb

私はまだフォーマットyyyy-MM-ddを渡すことに関して問題を抱えていました、しかし、私はDate.cshtmlを変更することによってそれを回避しました:

@model DateTime?

@{
    string date = string.Empty;
    if (Model != null)
    {
        date = string.Format("{0}-{1}-{2}", Model.Value.Year, Model.Value.Month, Model.Value.Day);
    }

    @Html.TextBox(string.Empty, date, new { @class = "datefield", type = "date"  })
}
4
markpcasey

に返信MVC4 DataType.Date EditorFor Chromeでは日付値を表示しません、IEでは問題ありません

モデルでは、次の種類の宣言が必要です。

[DataType(DataType.Date)]
public DateTime? DateXYZ { get; set; }

OR

[DataType(DataType.Date)]
public Nullable<System.DateTime> DateXYZ { get; set; }

次の属性を使う必要はありません。

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

Date.cshtmlではこのテンプレートを使用してください。

@model Nullable<DateTime>
@using System.Globalization;

@{
    DateTime dt = DateTime.Now;
    if (Model != null)
    {
        dt = (System.DateTime)Model;

    }

    if (Request.Browser.Type.ToUpper().Contains("IE") || Request.Browser.Type.Contains("InternetExplorer"))
    {
        @Html.TextBox("", String.Format("{0:d}", dt.ToShortDateString()), new { @class = "datefield", type = "date" })
    }
    else
    {
        //Tested in chrome
        DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat;
        dtfi.DateSeparator = "-";
        dtfi.ShortDatePattern = @"yyyy/MM/dd"; 
        @Html.TextBox("", String.Format("{0:d}", dt.ToString("d", dtfi)), new { @class = "datefield", type = "date" })
    } 
}

楽しむ!よろしく、Blerton

3
Blerton Hoxha

日付の形式を制御する必要がある場合(つまり、yyyy-mm-dd形式だけでなく)、文字列型のヘルパープロパティを追加し、そのプロパティに日付バリデータを追加することもできます。そして、UI上でこのプロパティにバインドします。

    [Display(Name = "Due date")]
    [Required]
    [AllowHtml]
    [DateValidation]
    public string DueDateString { get; set; }

    public DateTime? DueDate 
    {
        get
        {
            return string.IsNullOrEmpty(DueDateString) ? (DateTime?)null : DateTime.Parse(DueDateString);
        }
        set
        {
            DueDateString = value == null ? null : value.Value.ToString("d");
        }
    }

そしてこれが日付バリデータです。

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class DateValidationAttribute : ValidationAttribute
{
    public DateValidationAttribute()
    {
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            DateTime date;

            if (value is string)
            {
                if (!DateTime.TryParse((string)value, out date))
                {
                    return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
                }
            }
            else
                date = (DateTime)value;

            if (date < new DateTime(1900, 1, 1) || date > new DateTime(3000, 12, 31))
            {
                return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
            }
        }
        return null;
    }
}
1
Martin Staufcik