5

I have the following class in a C# ASMX web service, not MVC or web forms project.

public class Hotel
{
    public int HotelId {get;set;}
    public string Name {get;set;}

    public Room[] Room { get; set; }

    [Range(0, 12, ErrorMessage = "Rating must be between 1 and 5")]
    public int Rating {get;set:}
}

public class Room
{
    [Required]        
    public int RoomId {get;set;}

    [Required]
    [StringLength(175)]
    public string Name {get; set;}
}

Using System.ComponentModel.DataAnnotations, as I able to valid like above ? If so how to I get the response back of the validation error ?

Also when the service starts it I reads in a Json data object like below.

  oHotelRequest = JsonConvert.DeserializeObject<Hotel>(sJson);
  HotelResponse oHotelResponse = BookingAPI.Hotel.Get(oHotelRequest);
  return JsonConvert.SerializeObject(oHotelResponse);

Or am I able to do the validation when de-serializing the object ?

neildt
  • 5,101
  • 10
  • 56
  • 107

1 Answers1

2

You may look at this webpage: http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx

  • Thanks for the link. I've updated my question with a reference to the class Room as public Room[] Room { get; set; }. How would this be validated too ? – neildt Jul 29 '13 at 11:26
  • Following on, if I create a new instance of the object like Hotel oHotel = new Hotel(); and they call the validator with firstly oHotel and then oHotel.Room it works. Is this the correct approach ? – neildt Jul 29 '13 at 12:05
  • First - If you don't add any validation to Room field in Hotel class - there wouldn't be any validation of this field. Moreover, as I test with little code snippet, there is no auto-nested validation in this way, so even you mark Room field as Required, you must manually validate these fields. But you can make it more automatic by follow the solution in supplied website: implement IValidatableObject to your classes. Then, in Hotel.Validate function you can force validation of Room field, using Room.Validate (of course Room must also implement IValidatableObject interface). – Robert Skarżycki Jul 29 '13 at 13:28
  • I've updated the question to show the Room class and it's attributes. I also found no auto nested validation too. – neildt Jul 29 '13 at 13:32
  • thanks, can you provide a sample code snippet for implementation of IValidatableObject for my classes ? – neildt Jul 29 '13 at 13:37
  • To be swift: look at this http://stackoverflow.com/questions/3400542/how-do-i-use-ivalidatableobject - implementing IValidatableObject means you have to validate fields by calling Validator.TryValidateProperty; apart from results from these callings, you can add your own validations and add custom ValidationResult to the returning list. – Robert Skarżycki Jul 30 '13 at 07:32