Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/24.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
C# DisplayFormat ApplyFormat编辑模式_C#_Asp.net_Asp.net Mvc 3 - Fatal编程技术网

C# DisplayFormat ApplyFormat编辑模式

C# DisplayFormat ApplyFormat编辑模式,c#,asp.net,asp.net-mvc-3,C#,Asp.net,Asp.net Mvc 3,我在C#中使用MVC 3,我有一个具有此属性的类 [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}", ApplyFormatInEditMode = true)] 我想在用户处于编辑模式时强制执行验证 数据库中的数据以如下格式存储 6/15/2009 1:45:30 PM 我收到这个错误 错误字符串的格式不正确 我相信问题出在你身上 DataFormatString = "{0:dd MMM yyyy}" 知道怎么修吗 0:dd-M

我在C#中使用MVC 3,我有一个具有此属性的类

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}", ApplyFormatInEditMode = true)]
我想在用户处于编辑模式时强制执行验证

数据库中的数据以如下格式存储

  6/15/2009 1:45:30 PM
我收到这个错误

错误字符串的格式不正确

我相信问题出在你身上

DataFormatString = "{0:dd MMM yyyy}"

知道怎么修吗

0:dd-MMM-yyyy
将使用类似2009年6月06日的字符串,而不是2009年6月15日的字符串


当获取格式不正确的
字符串时,您如何输入字符串?

属性
DisplayFormat
仅用于显示值。如果您设置了
ApplyFormatInEditMode
,则当数据显示在文本框(用于编辑)中时,它所做的只是将格式应用于数据的内容。这与验证无关

如果要使用指定的格式验证输入,则可能需要创建自己的
ValidationAttribute
,并使用
DateTime.ParseExact()
尝试确保其符合预期的格式。唯一的缺点是,除非您编写它,否则它不会附带客户端验证逻辑

我还没有测试这周四,但它应该给你一个开始

public class DateTimeFormatAttribute : ValidationAttribute
{
   public int Format { get; set; }

   public override bool IsValid(object value)
   {
        if (value == null)
            return true;

        DateTime val;
        try
        {
            val = DateTime.ParseExact(value.ToString(), Format, null);
        }
        catch(FormatException)
        {
            return false;
        }

        //Not entirely sure it'd ever reach this, but I need a return statement in all codepaths
        return val != DateTime.MinValue;
   }
}
那就是使用它的问题了。
[DateTimeFormat(Format=“dd-MMM-yyyy”)]

更新:对不起,我想我没有清楚地阅读您的问题。它抱怨回发数据的原因是因为您尝试使用的格式不是标准格式。在填充字段时,最好实现一个常用的联机日期选择器,而不是手动编辑或使用这样的非标准格式。自定义显示格式非常适合显示,但如果您想在编辑模式中使用默认的
DateTime.Parse
无法理解的自定义格式,则必须编写自己的ModelBinder,我相信这是我没有做过的,或者,您可以将viewmodel上的数据类型更改为string,并在action方法中自己解析它(您仍然可以使用我在本例中提供的验证器)。要消除错误(但在编辑模式下也会删除自定义格式),必须删除
ApplyFormatInEditMode
属性