2011-01-21 2 views
2

내가ASP.NET MVC ModelState.IsValid 나던 작업

[HttpPost] 
    public ActionResult Create(Topic topic) 
    { 
     if (ModelState.IsValid) 
     { 
      topicRepo.Add(topic); 
      topicRepo.Save(); 

      return RedirectToAction("Details", new { id = topic.ID }); 
     } 
     return View(topic); 
    } 

을 만들이 컨트롤러의 방법을했습니다이 편집

 [HttpPost] 
     public ActionResult Edit(int id, FormCollection formCollection) 
     { 
      Topic topic = topicRepo.getTopic(id); 
      if (ModelState.IsValid) 
      { 
       UpdateModel<Topic>(topic); 
       topicRepo.Save(); 
       return RedirectToAction("Details", new { id = topic.ID }); 
      } 
      return View(topic); 
     } 

에 대한 (의 .ascx) . 내가 주제를 만들려고하지만 난 그것을 정상

답변

8

을 편집하려고하면 작동하지 않는 경우

검증 작동합니다. 첫 번째 예에서는 작업 매개 변수로 모델을 사용하고 있습니다. 기본 모델 바인더가 요청에서이 모델을 바인딩하려고하면 자동으로 유효성 검사를 호출하고 작업을 입력하면 ModelState.IsValid이 이미 할당되어 있습니다.

두 번째 예에서는 작업에 모델이 없으며 키/값 컬렉션 만 있고 모델 유효성 검사가없는 것은 의미가 없습니다. 유효성 검사는 사용자의 예제에서ModelState.IsValid 호출 후 이 호출되는 UpdateModel<TModel> 메서드에 의해 트리거됩니다.

그래서 당신이 시도 할 수 :

[HttpPost] 
public ActionResult Edit(int id) 
{ 
    Topic topic = topicRepo.getTopic(id); 
    UpdateModel<Topic>(topic); 
    if (ModelState.IsValid) 
    { 
     topicRepo.Save(); 
     return RedirectToAction("Details", new { id = topic.ID }); 
    } 
    return View(topic); 
} 
+0

는 정말 고마워요! –

+1

FYI - ModelState.IsValid가 false 인 경우 UpdateModel이 발생합니다. Throw하지 않으려면 대신 TryUpdateModel을 사용하십시오. – Levi

+1

오류가있는 경우 반환보기 (항목)는 양식의 값 대신 데이터베이스에서 값을 반환합니다. 유효성 검사 오류가 표시되지 않습니다. – jlp