views:

215

answers:

2

In my asp.net mvc application i have service layer, which operated with business object, pass its to repository layer and return to controller. No i can't decide where i need to validate object. First place - use data annotation validation with attribute of component model annotation in business objects class, for example:

[AcceptVerbs("POST")]
 public ActionResult Edit(Source src)
 {
  if(!ModelState.IsValid){   
            return View("EditSource", src);

  _sourceService.SaveSource(src);

  return RedirectToAction("Index");
 }

[MetadataType(typeof(Source.MetaSource))]
public class Source
{
 private class MetaSource
 {
  [Required]
  public string Name { set; get; }
  [Required]
  public string Url { set; get; }
 }

 public int? ID { set; get; }
 public string Name { set; get; }
 public string Url { set; get; }

 public Source()
 {
  ID = null;
 }

Second way - validate objects in service layer, by passing validation dictionary to service layer, for example:

 [AcceptVerbs("POST")]
 public ActionResult Edit(Source src)
 {
  if (!_sourceService.ValidateSource(src)){   
            return View("EditSource", src);

  _sourceService.SaveSource(src);

  return RedirectToAction("Index");
 }

public bool ValidateSource(Source srcToValidate)
 {
  if (string.IsNullOrEmpty(srcToValidate.Name))
   _validationDictionary.AddError("Name", "Name is required.");
  else
   if (srcToValidate.Name.Trim().Length == 0)
    _validationDictionary.AddError("Name", "Name is required.");

  if (string.IsNullOrEmpty(srcToValidate.Url))
   _validationDictionary.AddError("Url", "Url is required.");
  else
   if (srcToValidate.Url.Trim().Length == 0)
    _validationDictionary.AddError("Url", "Url is required.");

  return _validationDictionary.IsValid;
 }

I think of create client side validation, and add localization to validation errors, also i need create custom rules with calls to database, etc. What pros and cons of this 2 way, or maybe I need choose another way ?

+2  A: 

The asp.net website offers guidance for three cases:

These are probably worth reading before making any decisions.

Colin Desmond
+1  A: 

Definitely worth reading up on the various options - choose whichever you think best suits your needs and style.

However, you will almost certainly end up creating a validation function on your service at some point to cope with business rules, so that may be the tie-breaker :-)

Heres a few extra links which may be useful too:

chrisb