I have page with a simple table and advanced search form. I pass List<Customers> to the model:
View(List<Customers>);
So what is best way to pass and return data to the search form? I want to use validation or something but I think passing data through ViewData is not good idea. Any suggestions?
You should wrap all your data that is required by you view in a model specific to that view. The advantage to this is you could also include your search criteria in the model which would be empty at first but when your search posted, the model would automatically contain your search criteria so you could reload it when passing back the results. This will help maintain your state between post’s as well.
This also allows all your view’s data to be type safe where
ViewDatawould not be.Eg:
When you return back the
List<Customer>the search criteria would already be filled in your model from the post so your view can default the search criteria back to the corresponding controls (assuming your search results and search inputs controls are on the same view).For example, in your post you would accept a
CustomerSearchViewModel. Then all you need to do is get your list of customers and add it back to the model and return the same model.You could also add the validation attributes to your model properties to leverage the built in validation in MVC. This would not be possible if you were using
ViewDatato pass this data around.You have to also consider the ‘next guy’. It’s cleaner when all the data that the view requires is located in a single class. This way they don’t have to hunt through the code to discover if
ViewDatais being used and what data is actually being passed around in it.ViewDatais still an option for passing data but I try to minimize the use of it if at all possible.