Alternative for ViewBag in MVC3

I have an MVC3 web application where I need to implement database search functionality. I am creating a ViewModel class for my search form in order to get the search parameters from View to controller. I can successfully get all my search parameters (including search query and check boxes if the user wants to narrow the search) in my controller class and get data from the database using the repository template

var searchResult = _repository.GetItems(searchParms, chkbox1, chkbox2, ..., chkbox10) 

After that, I pass my search request to the pagination assistant, for example

 var paginatedSearchResult = new PaginatedList<Items>(searchResult, page ?? 0, pageSize); 

I will display the extracted data on my browse page

 return View(paginatedSearchResult) 

The problem that I encountered is, in addition to the data from the database, also show the query string and topic (for which the checkbox was checked) on my browse page so that the user can see what they were looking for. I did not find a suitable solution for this and had to use ViewBag. And now my Controller page looks ugly with over 10 ViewBag. I know that this requires a good solution, but I cannot find it. All suggestions will be highly appreciated.

Thanks ACS

+4
source share
3 answers

You're too close already. You have a ViewModel that you use to search - so you obviously know how to create a view model. Just create a new ViewModel in which the current ViewModel will be displayed as a property and the database search model as a property.

  public class SearchViewModel
 {
     public YourExistingSearchOptionsViewModel SearchViewModel {get; set}
     public PaginatedList SearchResults {get; set;}
 }

obviously this is very rude - but hopefully you get this idea.

+2
source

The direct answer to the question - an alternative for the viewbag in mvc - is the strongly typed ViewModel classes. Take a look at Create View Models

+3
source

I think you can find the strongly typed property "ViewData"

0
source

All Articles