ViewModel with restricted validation or 2 forms with shared field?
I have been struggling to find a solution to this issue for some time now. Basically I have a View that has a field at the top where the user enters a payment amount. I then have 2 forms for 2 different payment methods. The开发者_如何学C first method is payment via card where card details are entered. The second is payment via a registered account where an account number is entered. When the user submits either form I need to also submit the payment amount from the field at the top of the view.
Currently I have implemented this using just a single form using a ViewModel which has 3 properties (sub models), the PaymentAmount Model, the PaymentCardDetais Model and the AccountDetais Model. The problem with this is that on submission, all model fields in the viewModel get validated. Obviously the user is going to always enter an amount but will only enter either card details OR account details. I'm not sure if this is the best way to implement this - any thoughts on this would be much appreciated. If it is te best way then I need to find a way to avoid validation on all the viewmodels sub models - is this possible?
Thanks in advance for your help. James
You're right that the user will always enter an amount for both cases, but if I were you I would just avoid the DRY principle so useful when coding but not that much in terms of user interface and go with two independent forms one for each payment type and have an amount field in each one of them.
This way you solve your validation and form submitting problems.
Another option, if you really don't want to have two amount fields on the page I would consider letting the user first choose the payment method and then showing him only the form with the fields for the selected payment method.
精彩评论