问题
I am developing an MVC 5 app using EF 6 database first approach. I have a certain validation which is required for fields in many of my models. I am using remote validation for validating them. Since it was being used in a lot of models so I am trying to go for a generic method.
For that matter I made an Interface named IEntity which includes all properties being used in my models. Then I did the following for my Validation method:
[HttpPost]
public JsonResult UniqueCheck<T>(T code) where T : class, IEntity
{
MyEntities db = new MyEntities();
if (db.Set<T>().Any(x=>x.S1 == code.S1))
{
return Json("Already Exists!");
}
else
{
return Json(true);
}
}
And following is how I am calling the validation on properties in models:
[Remote("UniqueCheck", "Rules", HttpMethod = "POST")]
public string S1 { get; set; }
But the problem is that the validation is not working and when I checked in the browser console I got that the validation is actually going into the method but there was a 500(Internal Server Error) returned.
I know that the problem is with T written with method name because when I removed the generics and hardcoded my model name, it works fine.
I only want to use MVC's remote validation and I would be very happy to get this generic method working because otherwise it would be a copy/paste on a lot of locations.
来源:https://stackoverflow.com/questions/33414745/generic-remote-validations-in-mvc-5