Help with Model Validation

Sorry to bother you, I just have a quick question that is turning my head…

My question is: is possible for the validation to validate certain properties only? If I send 2 or 3 properties, validate only those and not every single property in the model…

I have a model called LOCATION with many required properties as follow:

public class Location
{

[Required]
public int? CityId { get; set; }
[Required]
public int? ZoneId { get; set; }

[Required]
public string Name{get;set;}
}

My LOCATION object has many required fields. What I did is… I created a form with only 2 fields, cityId, and ZoneId then I submitted the form, the problem is the validation object return errors for the whole object, in other words, if I send cityId and ZoneId, it will say both values are ok but the general validation always returns Invalid, because it is expecting the values for the other fields.

I tried using something like

public async Task AddLocation(
[Bind((new string { “CityId”, “ZoneId” }))] Location location
){

}

But it does the same thing, it validates every single property of the model… Some say that I have to create a ViewModel but why should I re-create the properties of the model and have 2 different ones? Please help.

If your adding a record and the fields are required if you do not put anything in those it will throw a validation error since the fields are null you can’t really escape that.

One thing you could do is still populate the fields in your action when you post before the Model.IsValid check or prepopulate them with hidden fields in your view when your load your Add Record View, then once you post they will have something in it.

Except that creating another view model just for this form might be your other only option. (just based of my experience in the past) someone else here might have another option.

This is what’s fun with ViewModels you can literally have a view model for each views if you want.

In cases like that i make a ViewModel with just those 2 properties and make them both required.

It really comes down to a conceptual question around why you want to accept an object that “is not valid”.

If it is a reason such as you are building your object iteratively (say, through a wizard-type interface), then you should probably take an approach where you have a ViewModel for each step that can enforce it’s own requirements. At the end, you map that ViewModel to your Location and validate that as a whole. And that makes sense, because in this case you are not working with a Location - you are instead working with some other construct that simply happens to share some of the same properties as a Location.

If, on the other hand, it is because you will never have those fields, then your Model is wrong.

.NET Foundation Website | Blog | Projects | Code of Conduct