Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.MVC3 ModelState.IsValid not include RemoteAttribute checking

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?

like image 361
daniel Avatar asked Nov 05 '22 06:11

daniel


1 Answers

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.

like image 129
J.P. ten Berge Avatar answered Nov 11 '22 16:11

J.P. ten Berge