Remote Data Annotation in ASP.NET MVC

In this blog, I will create a small sample demonstrating how "Remote" data annotation attribute works in ASP.NET MVC.
Data annotations in MVC are a helpful way to do a lot of custom data validation on the client side. However, sometimes you have a need where the property needs to be validated on the server side. MVC has a Remote attribute that helps you in doing just that. 

Let's say that you have a simple model to edit a music album. And, it has an album art URL, Title and Price properties. Let's say the server validation that we want is on URL and the condition is that URL should have title in it and if price is above 5, it should contain "amazon.com". This particular validation you can do on the client side as well but there might be other complex validation for which you need to make a server call. I chose this example because its simpler and shows how other properties can be passed (Title and Price in this case) and how error message can be configured. Let's take a look at the code:

Controller: Has a action method which gets all the 3 properties and validates the condition and returns the result as JSON.



ViewModel: Has the Remote attribute which configures the controller, action method, additional fields and error message.



Every time we edit and move the focus out of Album Art URL property, this validation is fired on the server side.





No comments: