MVC 3 Razor-Partial Validation of Model

2019-08-26 10:08发布

问题:

I am currently working on a project in MVC 3 where I am leveraging Entity Framework to persist one data model over two Views which each contain one HTML Form (similar to wizard-based design).

Yet after the user fills out the appropriate fields on the first View and submits the form, client-side validation for the entire model is triggered, and validation errors are shown for fields that will not even be available for input until the second View instantiates.

I have currently implemented a workaround where I simply turn off client-side validation for the first View entirely, but I am certainly not keen on the idea of populating my model with data that has not been validated at all. This is bad. M'kay.

Is there any way to partially validate the fields on the first View and not trigger valdiation for the whole data model?

回答1:

That's where ViewModels comes. Instead of directly binding the domain model with the views, you should create view models over them and bind to the views.



回答2:

If you are not required to put validation on the EF models directly then you can use the MetadataType to do partial validation as needed. Take a look at my long example here on stackoverflow.



回答3:

Thanks for the input all. However, I was able to obtain a solution in a very simple way. By placing the following code in the HttpPost element of the first View...

if (ModelState.IsValidField("FirstField") && ModelState.IsValidField("SecondField")) return RedirectToAction ("NameOfAction", model); else return View();

...I was able to achieve partial field validation. However, this field-specific approach will ONLY work provided the Submit button on the first View has class "cancel" and the additional validation errors that are generated (for the fields that are NOT present on the first View) are manually cleared before the above if statement. To do this, use:

ModelState["FieldName"].Errors.Clear();

No major change in architecure. No partial Views. No handing off unvalidated Data.

Works very well...

NOTE: If the second View loads with validation errors, use:

ModelState.Clear();

in the Action where the second View is initially called. This will make the second View load clean and error free, while still showing the validation errors later upon final form submission.