What is better way to validate business rules in ASP.NET MVC application with 3 layer architecture?

安稳与你 提交于 2019-11-28 21:41:44

I would avoid using exceptions for validation purposes but rather have methods that return true/false. Obviously for some tasks where validation is data at the data tier (for example enforcing database constraints) you could use exceptions.

You may take a look at the following tutorial about validating at the service layer.

Kon

First of all, do not throw Exceptions as a way of validating data - that's a way too expensive operation, instead of graceful handling of invalid data.

In general, when working with an MVC/ASP.NET web application, you typically want to do validation on the client-side as well as on the server side. While your current custom validation is simple enough, you'd have to duplicate it on the client and server, which is annoying - now you have two places to maintain a single validation routine.

For this reason using data annotations via attribute on your model properties is very handy. Check out: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

Additionally, you seem to need to do custom validation, and not just simple required/max length checks. For that you can define your own custom attributes. Check out: http://msdn.microsoft.com/en-us/library/cc668224.aspx and How to create custom validation attribute for MVC

You may also want to leverage remote validation. For that check out: http://bradwilson.typepad.com/blog/2010/01/remote-validation-with-aspnet-mvc-2.html and http://weblogs.asp.net/imranbaloch/archive/2011/02/05/new-validation-attributes-in-asp-net-mvc-3-future.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!