2011-12-08 28 views
1

我使用具有DataAnnotations屬性[Required]的兩個屬性爲登錄表單(具有用戶名和密碼字段)和視圖模型的部分視圖。使用ajax發佈的表單使用DataAnnotations返回PartialView進行驗證

在客戶端我有一個形式正確配置爲經由AJAX發佈,並且實際上被正確到達動作。

你能告訴我,如果任何這兩個選項是使用數據註釋驗證*或如果我完全錯了Ajax表單後的最佳做法? (我把一些評論在這個問題相關的代碼)

選項A

if (ModelState.IsValid) 
{ 
    //Do whatever with database, session, etc... 
    return Json(new { error:false; }); 
} 
else 
{ 
    //The html returned by this code comes with css-class="input-validation-error" 
    //for elements whose values didnt pass the validation 
    //should i use Jquery in client to replace actual html of the partial view 
    //by this resulting html????? 
    return PartialView("Login", usersubmitted); 
} 

選項B

if (ModelState.IsValid) 
{ 
    //Do whatever with database, session, etc... 
    return Json(new { error:false; }); 
} 
else 
{ 
    //I could return a Json array with all validation errors that happened 
    //and in client side use Jquery to add the css-class "input-validation-error" 
    //to those html elements whose id matches with the values in returned array. 
    return Json(
       new{ 
         {validation-error:"UserName"}, 
         {validation-error:"Password"} 
        } 
       ); 
} 

回答

1

選項B將是我的偏好,因爲它似乎維持通過將顯示和渲染決策完全掌握在View本身的手中,View和Controller之間的關注更加分離。控制器只是簡單地通知視圖中有問題的元素。