2012-02-07 3 views
1

내 모델 분야 :은 빈 문자열 필드에 잘못된 ModelState.IsValid 번호와 빈 문자열을 받아

[DisplayName("Height")] 
[RegularExpression (@"^\d*$", ErrorMessage="Height must be a number or left out blank")] 
public string Height { get; set; } 

[DisplayName("Width")] 
[RegularExpression(@"^\d*$", ErrorMessage = "Height must be a number or left out blank")] 
public string Width { get; set; } 

내보기 :

[HttpPost] 

public ActionResult Edit(MyModeltype model) 
{ 
    model.Width = String.IsNullOrEmpty(model.Width) ? "" : model.Width; //NEEDED? 
    model.Height = String.IsNullOrEmpty(model.Height) ? "" : model.Height; //NEEDED? 

    if (ModelState.IsValid) 
     SaveSettings(model); 

    return View("SomeView"); 
} 

I을 : 컨트롤러 액션에서

<%= Html.LabelFor(x => x.Width) %>: 
<%= Html.TextBoxFor(x => x.Width) %> 

<%= Html.LabelFor(x => x.Height) %>: 
<%= Html.TextBoxFor(x => x.Height) %> 

빈 텍스트 상자를 제공하면 Model.Width 및 .Height는 null로 전달되고 ModelState.IsValid는 false입니다. 빈 문자열을 전달할 수 있어야합니다. regex 속성을 생략하면 같은 문제가 발생하므로 정규식이 아닙니다. 고맙습니다!

답변

0

시도가 모델의 속성에 DisplayFormat 속성을 추가 :

[DisplayFormat(ConvertEmptyStringToNull = false)] 
[DisplayName("Height")] 
[RegularExpression (@"^\d*$", ErrorMessage="Height must be a number or left out blank")] 
public string Height { get; set; } 

[DisplayFormat(ConvertEmptyStringToNull = false)] 
[DisplayName("Width")] 
[RegularExpression(@"^\d*$", ErrorMessage = "Height must be a number or left out blank")] 
public string Width { get; set; } 

이 빈 텍스트 상자 값이 NULL로 변환되지 않습니다 보장합니다.

또는 명시 적으로 빈 문자열에 널 (null)로 변환하기 위해 getter 및 setter를 정의 할 수 있습니다 :이 도움이되지 않았다

private string _width; 
public string Width 
{ 
    get { return _width ?? string.Empty; } 
    set { _width = value ?? string.Empty; } 
} 
0

보기에 오류 메시지가 표시되지 않습니다. 그래서 그게 문제의 원인이 될지 모르겠지만 확실하지는 않습니다. 어쨌든 이것을 시도하고 작동하는지 확인 :

<%= Html.LabelFor(x => x.Width) %>: 
<%= Html.TextBoxFor(x => x.Width) %> 
<%= Html.ValidationMessageFor(x => x.Width) %> 

<%= Html.LabelFor(x => x.Height) %>: 
<%= Html.TextBoxFor(x => x.Height) %> 
<%= Html.ValidationMessageFor(x => x.Height) %> 
+0

. 디버깅 목적 이었습니까? – mishap

+0

아니요 모델 속성의 정규식이 실패 할 경우 프레임 워크가 오류 메시지를 표시하도록 기본 제공됩니다. 클라이언트 측 유효성 검사가 제대로 작동하도록하려면 포함시켜야합니다. 또한 필수로 표시되지 않은 필드에 빈 문자열을 사용하면 효과가 있습니다. 모델에서보기로 올바르게 설정되지 않은 다른 속성이 있습니까? 그러면 모델 상태가 유효하지 않게됩니다. –