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 ?

0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

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 ?
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 ?
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).
I've updated the question to show the Room class and it's attributes. I also found no auto nested validation too.
thanks, can you provide a sample code snippet for implementation of IValidatableObject for my classes ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.