2011-09-03 9 views
0

Ajax에서 제출하는 양식으로 ASP.NET MVC 유효성 검사 (주로 Fluent Validation에 관심이 있습니다)를 통합하는 편리한 방법이 있습니까?Ajax 양식 유효성 검사

답변

1

이것을 달성하는 가장 쉬운 방법은 해당 양식을 부분으로 배치 한 다음 AJAX를 사용하여 제출하는 것입니다. POST를 처리 할 컨트롤러 조치는 모델이 유효한지 확인하고 유효성 검증 오류를 표시하기 위해 부분을 리턴하지 않는지 점검합니다.

<div id="myform_container"> 
    <!-- The _Foo partial will contain a form --> 
    @Html.Partial("_Foo") 
</div> 

및 제출 처리 할 컨트롤러 액션 :

[HttpPost] 
public ActionResult Foo(SomeViewModel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     return PartialView("_Foo", model); 
    } 

    // TODO: process the results and inform the user that everything went fine: 
    return Json(new { success = true }); 
} 

이제 남은 모든 별도의 자바 스크립트 파일에이 양식을 AJAXify하는 것입니다

$(function() { 
    // Use delegate to preserve the .submit handler when we refresh the container 
    $('#myform_container').delegate('form', 'submit', function() { 
     $.ajax({ 
      url: this.action, 
      type: this.method, 
      data: $(this).serialize(), 
      success: function(result) { 
       if (result.success) { 
        // the server returned JSON 
        alert('thanks for submitting'); 
       } else { 
        // the server returned the partial => update the DOM 
        $('#myform_container').html(result); 
       } 
      } 
     }); 
     return false; 
    }); 
}); 
을 예를 들어