views:

34

answers:

2

Hi 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?

A: 

Rather than passing just a list of items to your View, create a class which contains your list of items and any other data you might need, i.e. a ViewModel.

public class CustomerSearchViewModel {
    public IEnumerable<Customer> Customers { get; set; }
    public string SearchTerm { get; set; }
}

.....

var viewModel = new CustomerSearchViewModel { 
                  Customers = customerList,
                  SearchTerm = searchTerm
                };

return View(viewModel);
Nathan Taylor
+1  A: 

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 ViewData would not be.

Eg:

public class CustomerSearchViewModel
{
    public List<Customer> Customers { get; set; }

    // your search criteria if you want to include it
    public string SearchFirstName { get; set; }
    public string SearchLastName { get; set; }
    public int SearchCustomerID { get; set; }
    // etc...
}

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.

// assuming you have accepted a CustomerSearchViewModel named model
model.Customers = GetCustomersForSearchCriteria(model.SearchFirstName,
    model.SearchLastName, model.SearchCustomerID);
return View(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 ViewData to 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 ViewData is being used and what data is actually being passed around in it.

ViewData is still an option for passing data but I try to minimize the use of it if at all possible.

Kelsey