.NET MVC Custom validation (without data annotation)

use .NET MVC and code-first EF to implement of requested functionality. Business objects are relatively complex and I use System.ComponentModel.DataAnnotations.IValidatableObject to validate business object. Now I'm trying to find the way, how to show validation result from business object, using MVC ValidationSummary without using data annotations. For example (very simplified):

Business Object:

    public class MyBusinessObject : BaseEntity, IValidatableObject
        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
           return Validate();
        public IEnumerable<ValidationResult> Validate()
           List<ValidationResult> results = new List<ValidationResult>();

           if (DealType == DealTypes.NotSet)
                results.Add(new ValidationResult("BO.DealType.NotSet", new[] { "DealType" }));

           return results.Count > 0 ? results.AsEnumerable() : null;

Now in my MVC controller I have something like this:

    public class MyController : Controller
        public ActionResult New(MyModel myModel)
           MyBusinessObject bo = GetBoFromModel(myModel);
           IEnumerable<ValidationResult> result = bo.Validate();
           if(result == null)
               //Save bo, using my services layer
               //return RedirectResult to success page

           return View(myModel);

In view, I have Html.ValidationSummary();. How I can pass IEnumerable<ValidationResult> to the ValidationSummary?

I tried to find an answer by googling, but all examples I found describes how to show validation summary using data annotations in Model and not in Business object.



Add property, say BusinessError, in the model

in the View do the following

  @Html.ValidationMessageFor(model => model.BusinessError)

Then in your controller whenever you have error do the following

ModelState.AddModelError("BussinessError", your error)

Need Your Help

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.