Jatin
Jatin

Reputation: 4063

Exclude nested properties from binding - [Bind(Exclude="SomeProperty")]

I have a simple ViewModel as given below

[Bind(Exclude = "State")]
public class CityViewModel {
    public int Id {get;set;}
    public int StateId { get; set; }
    public City City { get; set; }
}

The City property has a navigation reference to "State" Entity. In my view I am trying to add a new City, using the CityViewModel above. When adding city, I want the MVC to neglect the "City.State" property, so that it will not be bound and validated. So I use the [Bind(Exclude = "State")] on my CityViewModel. Surprisingly, in the controller, I get a model error for the "City.State" field (which I am trying to exclude from bind and validation).

How do I tell the MVC to neglect "City.State" property from binding and validation?

Edit: I have also tried [Bind(Exclude = "City.State")] but doesn't work. I still get Model.IsValid false.

Upvotes: 1

Views: 1222

Answers (1)

objectbox
objectbox

Reputation: 1281

Validation is a separate step from the binding and will always work with all properties of the model, so bind exclude would not prevent from validation of the City.State

You can call

ModelState["City.State"].Errors.Clear();

before checking Model.IsValid.

P.S. I would preffer to add another viewmodel class with correct set of properties then using workaround I mentioned above.

Upvotes: 2

Related Questions