Requred field validate MVC

2019-08-31 09:41发布

问题:

I have this scenario.

I have a form A and form B. both of the forms uses a single model. there are 10 fields in the model, all of the fields are Mandatory(Required)..

Form A uses first 5 (1,2,3,4,5) fields of the models and Form B user the remaining (6,7,8,9,10) fields.

So, when I submit form A it asks me for the required fields (6,7,8,9,10) to be filled and the same is the case with form B, it asks me for (1,2,3,4,5) field to be provided. how can I make sure that only those field are considered required which are available on the Form.

回答1:

This is possible by using View Models so your views will interact with relevant view model and then view model will interact with model. Keep in mind that view models contain only fields relevant specific to model. SO here are steps

1) Make two view models A with fields (1,2,3,4,5) and B with fields(6,7,8,9,10)

2) Views will submit relevant fields to their view models then you can submit to model in two ways

a) On submission of View A Insert first five values and insert next five fields with dummy or default values. And when View B is submitted then Update this record's last five values with actual values.

b) Make another ViewModelAB containing all ten fields without required attribute, Make an object of this ViewModelAB and fill it on the submission of both View Models (i.e. A and B). When all the fields are filled then submit it to actual database model

Please ask if you need further assistance



回答2:

I can think two ways to do what you need:

  1. Create two models with all the fields, but with the RequiredAttribute only on the ones you need in each form. all the field so you can map with each others without problem;

  2. Instead of using RequiredAttribute try to use RemoteValidationAttribute and, based on the form making the call, check if you should throw a required error or not;

An other option would be to disable clientside validation and perform only the server side one. I mean, in any ways you should always do a server side (check the business rules) validation before persisting your model.