I define a variable as
public class EditModel
{
[Remote("IsNameAvailable", "Home", ErrorMessage = "Name is in use.")]
[Display(Name = "Name")]
public string Name{ get; set; }
}
and in the Home controller
public JsonResult IsNameAvailable(string name)
{
if (duplicate)
return Json(false, JsonRequestBehavior.AllowGet);
else
return Json(true, JsonRequestBehavior.AllowGet);
}
but when I check the ModelState.IsValid in the Save action, it always return true even I can see the error message display on the View.
public ActionResult Save(EditModel editModel)
{
if (!ModelState.IsValid)
{
//Return to view and display error in view
return View("Home", editModel);
}
//Input data is valid and save record
Repository.Save(editModel.Name);
}
How can the ModelState check also the Validation rules by RemoteAttribure in a model?
You've got two options. You can implement either the IDataErrorInfo or IValidatableObject interface and redo the validation there. These interfaces are supported out-of-the-box by MVC and your ModelState will reflect this.
Your other option is creating your own attribute that derives from RemoteAttribute. In this custom attribute, add logic for applying the same validation server-side.
The last option is the one I would go for, but that does take up a bit more time. This question should help you with it though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With