ASP.NET MVC Validation Groups?

前端 未结 2 1550
执念已碎
执念已碎 2020-12-14 21:13

I have a form in which I would like to require different fields depending on which submit button is pressed. Example: Field A is required if you press Submit Button 1, but

2条回答
  •  春和景丽
    2020-12-14 22:07

    You could give the same name to each submit button and different value. Then have a property on your view model having this name of type string. When the form is submitted its value will match the value of the button that was clicked. Now you could design a custom validator attribute that will be used to decorate your view model with. In its IsValid implementation you will fetch the instance of your view model and based on the value of the special property you will perform the validations. It's ugly, I know, but DataAnnotations are really useful for simple validation situations, but when you start writing real world applications you realize their limitations.

    Personally I use FluentValidation.NET and a scenario like the one being described here is pretty trivial to implement.

提交回复
热议问题