2011-09-03 239 views
0

是否有任何方便的方式將ASP.NET MVC驗證(我主要關注Fluent驗證)與Ajax提交的表單進行整合?Ajax表單驗證

回答

1

實現此目的的最簡單方法是將這些表單放入partial中,然後使用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 }); 
} 

現在,所有剩下的就是在一個單獨的JavaScript文件到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; 
    }); 
});