Making it valid, and seeing whats not

Last post 07-03-2009 11:52 AM by CodeHobo. 7 replies.

Sort Posts:

  • Making it valid, and seeing whats not

    07-02-2009, 1:19 PM
    • Member
      62 point Member
    • Svevarn
    • Member since 09-15-2003, 10:11 AM
    • Posts 161

     

    Hello

     

    I'm trying to save using the Create action to database. I have made a form that shows some of the fields that you can edit. However it always runs the "catch" when I try to save. I dont want to fill in data to all the field in the database, just some of it.

     

    [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult CreateObject(BookingObject bookingobject)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        bs.SaveBookingObject(bookingobject);
                    }
                    catch {
                        ModelState.AddModelError("SomeError", "errrrrrrrrror");
                    }
                }
    
                return View("CreateObject", new BookingObjectsAdminModel { BookingObject = bookingobject });
            }


     

     

    So my questions:

     

    1) Can I specify which fields needs to be filled in in the actionmethod?

    2) Can I instead of ModelState.AddError somehow list all "violations"?

     

    Thanks in advance

    /S

  • Re: Making it valid, and seeing whats not

    07-02-2009, 1:44 PM
    • Contributor
      2,599 point Contributor
    • CodeHobo
    • Member since 08-17-2005, 2:58 PM
    • Southern California
    • Posts 393

    1) How are you doing the validation in SaveBookingObject? Depending on the validation scheme you should be able to customize which fields are required in there.

    2) The way I list is all violations is to create RuleViolationException that extends Exception and adds and IEnumerable of rule violations like so

     public class RuleValidationException : Exception
        {
            public IEnumerable<RuleViolation> RuleViolations { get; private set; }
            public RuleValidationException(string message, IEnumerable<RuleViolation> ruleViolations)
                : base(message)
            {
                RuleViolations = ruleViolations;
            }
        }

    In the respoistory I throw a RuleValidationException and put all the violations in there and then catch it  and add it to modelstate. (you can do this either in the controller directly or in a service).
    try{
          bs.SaveBookingObject(bookingobject); 
    }
    catch (RuleValidationException e){
         var ruleViolations = e.RuleViolations;
         foreach (var violation in ruleViolations){
           ModelState.AddError(violation.PropertyName, violation.ErrorMessage);
        }
     }




  • Re: Making it valid, and seeing whats not

    07-02-2009, 1:53 PM
    • Member
      62 point Member
    • Svevarn
    • Member since 09-15-2003, 10:11 AM
    • Posts 161

     

    At the moment I have no validation in my "service-layer", method just look like this:

     public void SaveBookingObject(BookingObject bo)
            {
                _repository.SaveBookingObject(bo);
            }


     

    How shall I add something there and specify which fields are needed?

  • Re: Making it valid, and seeing whats not

    07-02-2009, 2:04 PM
    Answer
    • Contributor
      2,599 point Contributor
    • CodeHobo
    • Member since 08-17-2005, 2:58 PM
    • Southern California
    • Posts 393

    Take a look at this tutorial. It shows you how to do validation
    http://nerddinnerbook.s3.amazonaws.com/Part3.htm

    If you follow the example there you could add the validation to your entity object (in thise case BookingObject).


    Another way you can do it is directly in your  SaveBookingObject, but this may not be the cleanest approach.  You can do something like

    public void SaveBookingObject(BookingObject bo) {  
     var violations = ValidateBooking(bo);
      if(violations.Count() > 0){
        throw new RuleViolationException("error",violations);
      }
    
     _repository.SaveBookingObject(bo);  
    }  
    
    public IEnumerable<RuleViolation> ValidateBooking(BookingObject bo){
      if (String.IsNullOrEmpty(bo.Property))
            yield return new RuleViolation("Property is Required","Property");
    
      yield break;
    }


  • Re: Making it valid, and seeing whats not

    07-02-2009, 2:13 PM
    • Member
      62 point Member
    • Svevarn
    • Member since 09-15-2003, 10:11 AM
    • Posts 161

     

    Ok, thanks, I will look into that.

    Is there some easy way of making the error messages come from a resource file? (read: language-support)

    /S

  • Re: Making it valid, and seeing whats not

    07-02-2009, 2:32 PM
    Answer
    • Contributor
      2,599 point Contributor
    • CodeHobo
    • Member since 08-17-2005, 2:58 PM
    • Southern California
    • Posts 393

    The error message is just a string so you shouldn't have any problem reading it out  of a resource file.

    Take a look at this

    http://blog.eworldui.net/post/2008/05/ASPNET-MVC---Localization.aspx

    and this

    http://developmentalmadness.blogspot.com/2009/05/aspnet-mvc-globalizationlocalization.html

  • Re: Making it valid, and seeing whats not

    07-03-2009, 7:22 AM
    • Member
      62 point Member
    • Svevarn
    • Member since 09-15-2003, 10:11 AM
    • Posts 161

     

    public class RuleValidationException : Exception
        {   
            public IEnumerable<RuleViolation> RuleViolations { get; private set; }   
            public RuleValidationException(string message, IEnumerable<RuleViolation> ruleViolations)   
               : base(message)
            {   
                RuleViolations = ruleViolations;   
            }   
        }  


     

    where shall I put that? If I put it in controller I get:

    Error 1 The type or namespace name 'RuleViolation' could not be found (are you missing a using directive or an assembly reference?)

  • Re: Making it valid, and seeing whats not

    07-03-2009, 11:52 AM
    • Contributor
      2,599 point Contributor
    • CodeHobo
    • Member since 08-17-2005, 2:58 PM
    • Southern California
    • Posts 393

    RuleViolation the class isn't part of asp.net mvc. You have to define it manually. It's mentioned in the nerd dinner tutorial that I linked to earlir. Here is the class

    public class RuleViolation {
        public string ErrorMessage { get; private set; }
        public string PropertyName { get; private set; }
     
        public RuleViolation(string errorMessage, string propertyName) {
            ErrorMessage = errorMessage;
            PropertyName = propertyName;
        }
    }

    You can put it in the same folder as the controller, but a better location would be in the same namespace as the repository.

Page 1 of 1 (8 items)