开发者

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

I have a simple ViewModel as gi开发者_C百科ven 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜