2

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

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

我想在用户进入时强制执行验证EDIT MODE

数据库中的数据以datetime这样的格式存储

  6/15/2009 1:45:30 PM

我收到此错误

错误字符串格式不正确

我相信问题出在

DataFormatString = "{0:dd MMM yyyy}"

知道如何解决吗?

4

2 回答 2

6

DisplayFormat属性实际上仅用于显示值。如果您设置ApplyFormatInEditMode它,它还将在文本框中显示时将格式应用于数据内容(用于编辑)。它与验证无关。

If you want to validate the input using the format you've specified you'll likely have to create your own ValidationAttribute, and use DateTime.ParseExact() to attempt to ensure it meets the format you're expecting. The only draw back is it will not have an accompanying client side validation logic unless you write it.

I have not tested this thuroughly, but it should give you a start.

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;
   }
}

Then it's just a matter of using it. [DateTimeFormat(Format = "dd MMM yyyy")]

UPDATE: Sorry I donn't think I clearly read your question. The reason it's complaining about the data on postback is because the format you're trying to use is not a standard one. You might be better off implementing one of the common date pickers online to use when populating the field rather than letting it be hand edited or expecting a non-standard format like this. Custom display formats are great for displaying, but if you want to use a custom format for edit mode that the default DateTime.Parse doesn't understand you'd have to write your own ModelBinder I believe, and that's something I'd not done, alternatively you could change the data type on your viewmodel to string and the parse it yourself in the action method (you could still use the validator I provided in this case). To get rid of your error (but will also remove your custom format when in edit mode) you'd have to remove the ApplyFormatInEditMode property.

于 2012-11-06T21:01:14.190 回答
0

0:dd MMM yyyy将期望一个字符串,06 JUN 2009而不是6/15/2009.

String Not in Correct Format收到错误时如何输入字符串?

于 2012-11-06T20:04:11.377 回答