2009-09-01 2 views
2

David Hayden's BlogASP.Net MVC Tutorials과 같은 웹에서 유효성 검사 자습서와 예제를 수행하려고했지만 아래 코드를 얻을 수 없습니다. 실제 유효성 검증 오류를 표시합니다. 이처럼 보이는 모델 클래스의ASP.NET MVC : TryUpdateModel에서 설정 한 유효성 검사 메시지가 표시되지 않음 ValidationSummary

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Parent>" %> 

<%-- ... content stuff ... --%> 

<%= Html.ValidationSummary("Edit was unsuccessful. Correct errors and retry.") %> 
<% using (Html.BeginForm()) {%> 

<%-- ... "Parent" editor form stuff... --%> 

     <p> 
      <label for="Age">Age:</label> 
      <%= Html.TextBox("Age", Model.Age)%> 
      <%= Html.ValidationMessage("Age", "*")%> 
     </p> 

<%-- etc... --%> 

: 나는 이런 식으로 뭔가를 보이는 뷰가있는 경우

(나이가 int로 선언되어 있기 때문에) 내가 잘못된 시대를 입력 할 때마다
public class Parent 
{ 
    public String FirstName { get; set; } 
    public String LastName { get; set; } 
    public int Age { get; set; } 
    public int Id { get; set; } 
} 

, 예 : "xxx"(정수가 아님)보기 에 "Edit was Unsuccessful. Correct errors and 재 시도"메시지를 올바르게 표시하고 Age 텍스트 상자를 강조 표시하고 빨간색 별표 그 옆에 오류를 나타냅니다. 그러나 ValidationSummary에는 오류 메시지 목록이 표시되지 않습니다. 나 자신의 유효성 검사 (예 : 아래 LastName)를 수행하면 메시지가 올바르게 표시되지만 TryUpdateModel의 기본 유효성 검사에서 필드 값이 잘못된 경우 메시지가 표시되지 않는 것 같습니다. 여기

이 동작은 내 컨트롤러 코드에서 호출됩니다

[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult EditParent(int id, FormCollection collection) 
    { 
     // Get an updated version of the Parent from the repository: 
     Parent currentParent = theParentService.Read(id); 

     // Exclude database "Id" from the update: 
     TryUpdateModel(currentParent, null, null, new string[]{"Id"}); 
     if (String.IsNullOrEmpty(currentParent.LastName)) 
      ModelState.AddModelError("LastName", "Last name can't be empty."); 
     if (!ModelState.IsValid) 
      return View(currentParent); 

     theParentService.Update(currentParent); 
     return View(currentParent); 
    } 

나는 무엇을 그리워 했습니까?

답변

2

Microsoft에서 다운로드하여 ASP.NET MVC v1.0 source code을보고 실수로 또는 디자인 상으로는 적어도 기본적으로 원하는 작업을 수행 할 수있는 방법이 없음을 발견했습니다. 명백히 UpdateModel 또는 TryUpdateModel에 대한 호출 중에 Integer의 유효성 검사에 실패하면 잘못된 값에 대해 ModelState와 연결된 ModelError에 ErrorMessage가 명시 적으로 설정되지 않고 대신 Exception 속성이 설정됩니다. modelState에 대한 널 (null) 매개 변수가 전달됩니다

string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */); 

주의 : MVC ValidationExtensions의 코드에 따르면, 다음 코드는 오류 텍스트를 취득하는 데 사용됩니다. GetUserErrorMEssageOrDefault 방법은 다음과 같이 시작한다 : 그래서

private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState) { 
    if (!String.IsNullOrEmpty(error.ErrorMessage)) { 
     return error.ErrorMessage; 
    } 
    if (modelState == null) { 
     return null; 
    } 

    // Remaining code to fetch displayed string value... 
} 

의 ModelError.ErrorMessage 속성 (I가 선언 된 int 형 정수가 아닌 값을 설정하려고 할 때 그것이 것을 확인하는) 비어있는 경우, MVC는 계속된다 우리가 이미 발견 한 ModelState를 검사하는 것은 null이며, 따라서 Exception ModelError에 대해 null이 반환됩니다.

  1. 가 제대로 ErrorMessage가이 설정되지 않은 적절한 메시지를 반환하는 사용자 지정 유효성 검사 확장을 생성하지만 예외가 설정됩니다 : 그래서,이 시점에서이 문제에 대한 나의이 가장 좋은 해결 방법 아이디어가 있습니다.
  2. ModelState.IsValid가 false를 반환하면 컨트롤러에서 호출되는 사전 처리 함수를 만듭니다. 전처리 함수는 ErrorMessage가 설정되지 않은 Exception이 설정된 ModelState의 값을 찾은 다음 ModelState.Value.AttemptedValue를 사용하여 적절한 메시지를 파생시킵니다.

다른 아이디어?

+1

나는 똑같은 깨달음을 얻었지만 약간의 시행 착오를 겪었다. 당신의 # 2는 내가 결국해야만했던 것입니다. – Funka

+0

MVC3에서이 작업을 수행 할 수있는 방법이 있는지 알고 있습니까? 내 예외에서 ErrorMessage 속성으로 복사하는 전역 작업 필터를 만들려고하는데, 이상하게 여겨야한다! – mcintyre321

관련 문제