i have a partial view with a login form (with username and password fields) and a viewmodel for it with two properties with DataAnnotations attributes [Required].
On client side i have a form properly configured that is posted via ajax, and actually is reaching the action correctly.
Could you tell me if any of this two options is a best practice for ajax form post using Data Annotations to validate* or if i am totally wrong ? (i put some comments in the code related with this question)
Option 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);
}
Option 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"}
}
);
}
Option B would be my preference as it seems to maintain a stronger separation of concerns between the View and Controller by leaving the display and rendering decisions completely in the hands of the View itself. The controller is simply informing the View of the elements that are problematic.