2011-12-08 27 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之间的关注更加分离。控制器只是简单地通知视图中有问题的元素。