开发者

Alternative for ViewBag in MVC3

开发者 https://www.devze.com 2023-03-05 02:47 出处:网络
I have a MVC3 web application where I need to implement a database search functionality. I am creating a ViewModel class for my search form so that I get the search parameters from View to controller.

I have a MVC3 web application where I need to implement a database search functionality. I am creating a ViewModel class for my search form so that I get the search parameters from View to controller. I can successfully get all my search parameters (which includes search query and check boxes if user wants to narrow search) in m开发者_如何转开发y controller class and retrieve data from database using repository pattern

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

After this, I am passing my searchResult to pagination helper like

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

I am displaying the retrieved data in my view page

return View(paginatedSearchResult)

The problem, I am facing is, besides the data from the database, I also need to show the search query string and topic (for which checkbox was used) in my view page so that user can see what they searched for. I did not find any proper solution to this and had to use ViewBag. And now my Controller page looks ugly with more than 10 ViewBag. I know there must some good solution to this but I am not able to find it.Any suggestions will be highly appreciated.

Thanks, ACS


Direct answer to question's title is - alternative for viewbag in mvc is strongly typed ViewModel classes. Take a look at Create View Models


You are soooo close already. You have a ViewModel you are using for the search - so you obviously know how to create a view model. Just create a new ViewModel that has your current ViewModel as a property and the database search viewmodel as a property.

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

obviously that is very rough - but hopefully you get the idea there.


I think you might be searching for the strongly typed "ViewData" property

0

精彩评论

暂无评论...
验证码 换一张
取 消