ASP.NET MVC Model Binding/Validation Questions

Let’s say I render a strongly typed view MyReportView, strongly typed to MyReport model.

Let’s say the view has a text input (used to input a date), select of car makes, and another select of car models that is initially empty/disabled. Once the user puts in a date and selects a car make, via ajax I populate the models in the car models selection. For the sake of argument there are many other input controls that are irrelevant but also have their validation defined in the model. Lastly there is a Go button that eventually when all fields are populated/validated performs some action, perhaps runs some report.

Questions regarding best practices:

1) Should MyReport model contain the property and validation attributes for the car models select, even though it'll be populated by ajax call later against another action. If not then I have to manually put in the jQuery validate data attributes for relevant validation, so when eventually I press the Go button it's also a required field.

2) When making the ajax call to get the car models (after selecting a date and car make), I only need to submit the date and the car make to the server to get the options for the car models select. Let’s say I have an action called GetCarModels on my controller. What are the parameter(s) of that action? If I use simple types, a DateTime and int, model binding doesn't have any validation metadata, not allowing me to check ModelState.IsValid, so I have to roll my own validation in that action. If I make the parameter the entire MyReport model, then I'll end up with other properties in that model that are not yet populated and are in error state, as they are irrelevant to the operation of simply getting the car models. Or do I create another model that is only relevant to this action, and annotate it with proper validation metadata. If I choose the latter then I am repeating some things between the original MyReport model and the new one (for example the metadata for the date).

Pretty much all examples you see online are things like RSVP Forms, where an action displays the form, then submits the entire form back to the server, in such case it obviously makes sense to pitch and catch the same model to and from the view. However in the real world where I have a bunch of different ajax calls on a single page doing different things, utilizing different parts of the original model, I don't quite understand what the best practice is as far as model binding and server side validation.

by ChosenGSR via /r/csharp

Leave a Reply