ASP.MVC3 ModelState.IsValid does not include RemoteAttribute validation

I define the variable as

public class EditModel
{
    [Remote("IsNameAvailable", "Home", ErrorMessage = "Name is in use.")]
    [Display(Name = "Name")]
    public string Name{ get; set; }
}

and in the controller Home

public JsonResult IsNameAvailable(string name)
{
    if (duplicate)
        return Json(false, JsonRequestBehavior.AllowGet);
    else
        return Json(true, JsonRequestBehavior.AllowGet);
}

but when I check ModelState.IsValid in the Save action, it always returns true, even if I see an error message in 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);
}

[Problem]
How can ModelState also validate Validation rules using RemoteAttribure in the model?

+5
source share
1 answer

You have two options. You can implement the IDataErrorInfo or IValidatableObject interface and retry the validation there. These interfaces are supported due to the MVC box, and your ModelState will reflect that.

- , RemoteAttribute. .

- , , . .

+2

All Articles