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.
RemoteAttribute
makes an ajax call and sends the name/value pair of the property to the controller method, in the case of propertyS1
it sendsS1:someValue
so you method nedds a parameterstring S1
It does not send any other information (except the name/value pairs specified inAdditionalFields
if you use it) soT
is unknown. – EstaminetT
is undefined. TheRemoteAttribute
does not pass aclass
orinterface
to the method - just the name/value pair of the property. – EstaminetAdditonalFields
and render a hidden input in every view to store the class name then use reflection to initialize the class in your controller. Far more work than its worth. – Estaminet