Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc MVC4数据类型。日期编辑器用于赢得和#x27;t在Chrome中显示日期值,在Internet Explorer中显示精细_Asp.net Mvc_Asp.net Mvc 4_Editorfor - Fatal编程技术网

Asp.net mvc MVC4数据类型。日期编辑器用于赢得和#x27;t在Chrome中显示日期值,在Internet Explorer中显示精细

Asp.net mvc MVC4数据类型。日期编辑器用于赢得和#x27;t在Chrome中显示日期值,在Internet Explorer中显示精细,asp.net-mvc,asp.net-mvc-4,editorfor,Asp.net Mvc,Asp.net Mvc 4,Editorfor,我在模型上使用DataType.Date属性,在视图中使用EditorFor。这在和中运行良好,但在中显示的是一个日期选择器,而不是显示值,它只是以褪色的灰色文本显示“月/日/年” 为什么谷歌浏览器不显示这个值 型号: [DataType(DataType.Date)] public Nullable<System.DateTime> EstPurchaseDate { get; set; } [数据类型(DataType.Date)] 公共可为空的EstPurchaseDate{

我在模型上使用DataType.Date属性,在视图中使用EditorFor。这在和中运行良好,但在中显示的是一个日期选择器,而不是显示值,它只是以褪色的灰色文本显示“月/日/年”

为什么谷歌浏览器不显示这个值

型号:

[DataType(DataType.Date)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }
[数据类型(DataType.Date)]
公共可为空的EstPurchaseDate{get;set;}
视图:

Est。普尔。日期
@EditorFor(m=>m.EstPurchaseDate)


当您使用
[DataType(DataType.Date)]
装饰模型属性时,ASP.NET MVC 4中的默认模板将生成一个输入字段
type=“Date”


如果从模型中删除
[DataType(DataType.Date)]
,Chrome中的输入字段将呈现为
type=“datetime”
,并且也不会显示日期选择器。

我仍然对其传递格式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"  })
}

在MVC 3中,我必须添加:

using System.ComponentModel.DataAnnotations;
在添加属性时使用以下选项:

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

特别是如果您像我一样在.edmx文件中添加这些属性。我发现默认情况下.edmx文件没有此功能,因此仅添加属性是不够的。

回复MVC4数据类型。Date EditorFor在Chrome中不会显示日期值,在IE中很好

在模型中,您需要具有以下类型的声明:

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

在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" })
    } 
}
@模型可为空
@利用制度全球化;
@{
DateTime dt=DateTime.Now;
如果(型号!=null)
{
dt=(System.DateTime)模型;
}
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”})
}
其他的
{
//铬测试
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

在MVC5.2中,将Date.cshtml添加到文件夹~/Views/Shared/EditorTemplates:

@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)
}
@model DateTime?
@{
i词典和贡品;
对象对象属性;
if(ViewData.TryGetValue(“htmlAttributes”,out objAttributes))
{
htmlAttributes=作为IDictionary的对象属性??HtmlHelper.AnonymousObjectToHtmlAttributes(对象属性);
}
其他的
{
htmlAttributes=新的RouteValueDictionary();
}
添加(“类型”、“日期”);
字符串格式=(Request.UserAgent!=null&&Request.UserAgent.Contains(“Chrome”)?“{0:yyyy-MM-dd}”:“{0:d}”;
@文本框(“”,模型,格式,htmlAttributes)
}

作为Darin Dimitrov回答的补充:

如果您只希望此特定行使用特定(不同于标准)格式,则可以在MVC5中使用:

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

如果您需要控制日期的格式(换句话说,不仅仅是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;
    }
}
[AttributeUsage(AttributeTargets.Property,AllowMultiple=true,Inherited=true)]
公共类DateValidationAttribute:ValidationAttribute
{
public DateValidationAttribute()
{
}
受保护的重写ValidationResult有效(对象值,ValidationContext ValidationContext)
{
if(值!=null)
{
日期时间日期;
if(值为字符串)
{
如果(!DateTime.TryParse((字符串)值,过期))
{
返回新的ValidationResult(validationContext.DisplayName+“必须是有效日期”);
}
}
其他的
日期=(日期时间)值;
如果(日期<新日期时间(1900,1,1)|日期>新日期时间(3000,12,31))
{
返回新的ValidationResult(validationContext.DisplayName+“必须是有效日期”);
}
}
返回null;
}
}

Darin谢谢你,太棒了!在过去的两年里,你回答了我那么多的MVC问题,你太棒了!很好的答案,但我觉得这很吸引人,你必须强迫它只是为了让控件正常工作!对于所有标记为
[DataType(DataType.Date)]
的房产,如何“全球”进行标记,这样我就不必单独标记所有房产,以免丢失一些房产?达林,美国境外的美国人能做些什么?如何设置规格值,但显示自定义日期格式?ie,UK?@Marjannema-我使用了Matt Honeycutt的FailTracker()中的“ExtensionalModelMetadataProvider”。在Infrastructure文件夹下查看ModelMetadata。我使用了这些类,然后创建了IModelMetadataFilter的过滤器实现。调用TransformMetadata方法后,可以编辑元数据的“DisplayFormatString”和“EditFormatString”属性。希望这能让你走上正确的方向(顺便说一句,有一个很棒的使用故障跟踪器的pluralsight视频)谢谢Bernie。我没有因为选择器出现而感到麻烦,因为数据没有被输入到输入框中。不过这很好,Opera提供了一个日期选择器。使用Modernizer进行一些多边形填充如果它应该是一个日期,那么它应该作为
date
类型的输入来呈现。使用
datetime
作为变通方法是不合适的,因为它不能在语义上表示数据。如果你这样做,Chrome不会给你一个日期选择器。我正在使用您的解决方案,但正在修改,以便1)我
@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" })
    } 
}
@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)
}
@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })
    [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;
    }
}