2013-06-13 3 views
1

저는 Razor와 함께 ASP.NET MVC 4를 사용하고 있습니다. 내가 확인 메시지가 무엇입니까 (의 내가 내 텍스트 상자에 2013년 10월 20일가 있다고 가정하자) :왜 dateFormat 유효성 검사 오류가 발생합니까

The field MyNullableDateField must be a date 

내 모델 코드 :

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

내 면도기 :

@Html.EditorFor(m => m.MyNullableDateField, new { @class = "date" }) 

내 편집기 템플릿 :

@model DateTime? 
@Html.TextBox(string.Empty, (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "date" }) 

그런 오류?

+1

** ** [ASP.NET MVC3 - DateTime 형식] (http://stackoverflow.com/questions/7835614/asp-net-mvc3-datetime-format)의 ** 중복. 즉, 기본 모델 바인더에서는'DisplayFormat'이 무시되기 때문입니다. 자신의 모델 바인더를 만듭니다. – CodeCaster

답변

2

안드레이는

표시 형식은 뷰에서 사용하는 HTML을 헬퍼의 사용을 대부분입니다.

(@CodeCaster에서 올바르게 언급 한 것처럼) 필요한 것은 DateTime 유형의 사용자 정의 모델 바인더입니다. 사용자 정의 모델 바인더는 유형별로 등록 할 수 있으므로 MVC 런타임이 동일한 유형의 컨트롤러 조치에 인수를 볼 때마다 사용자 정의 모델 바인더를 호출하여 게시 된 값을 올바르게 해석하고 유형을 생성합니다.

다음은 a입니다.

public class DateTimeModelBinder : DefaultModelBinder 
{ 
    private string _customFormat; 

    public DateTimeModelBinder(string customFormat) 
    { 
     _customFormat = customFormat; 
    } 

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
    // use correct fromatting to format the value 
     return DateTime.ParseExact(value.AttemptedValue, _customFormat, CultureInfo.InvariantCulture); 
    } 
} 

날짜 시간

샘플 사용자 정의 모델 바인더 유형은 이제 날짜 시간에 대한 새로운 모델 바인더를 사용하는 MVC 말할해야합니다. 당신은 위해 Application_Start에서 새로운 모델 바인더를 등록하여이 작업을 수행 할 수 있습니다

protected void Application_Start() 
{ 
    //tell MVC all about your new custom model binder 
    var binder = new DateTimeModelBinder("dd.MM.yyyy"); 
    ModelBinders.Binders.Add(typeof(DateTime), binder); 
    ModelBinders.Binders.Add(typeof(DateTime?), binder); 
} 

신용 날짜 시간이 당신의 올바른 parth

시작을 얻을하는 데 도움이 ( http://blog.greatrexpectations.com/2013/01/10/custom-date-formats-and-the-mvc-model-binder/)

희망 바인딩 사용자 정의 모델이 우수한 기사로 이동

관련 문제