MVC3 中 ViewBag 的替代方案
我有一个 MVC3 Web 应用程序,需要在其中实现数据库搜索功能。我正在为我的搜索表单创建一个 ViewModel 类,以便将搜索参数从视图获取到控制器。我可以在控制器类中成功获取所有搜索参数(如果用户想要缩小搜索范围,则包括搜索查询和复选框)并使用存储库模式从数据库检索数据
var searchResult = _repository.GetItems(searchParms, chkbox1, chkbox2, ..., chkbox10)
之后,我将 searchResult 传递给分页助手,就像
var paginatedSearchResult = new PaginatedList<Items>(searchResult, page ?? 0, pageSize);
我显示的 那样我的视图页面中检索到的数据
return View(paginatedSearchResult)
我面临的问题是,除了数据库中的数据之外,我还需要在我的视图页面中显示搜索查询字符串和主题(使用了哪个复选框),以便用户可以看到什么他们寻找。我没有找到任何合适的解决方案,不得不使用 ViewBag。现在我的Controller页面看起来很丑,有超过10个ViewBag。我知道必须有一些好的解决方案,但我找不到它。任何建议将不胜感激。
谢谢, ACS
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 my 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题标题的直接答案是 - mvc 中 viewbag 的替代方案是强类型 ViewModel 类。看看 创建视图模型
Direct answer to question's title is - alternative for viewbag in mvc is strongly typed ViewModel classes. Take a look at Create View Models
你已经很接近了。
您有一个用于搜索的 ViewModel - 所以您显然知道如何创建视图模型。只需创建一个新的 ViewModel,将当前 ViewModel 作为属性,并将数据库搜索视图模型作为属性。
显然这很粗糙——但希望你能明白其中的意思。
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.
obviously that is very rough - but hopefully you get the idea there.
我认为您可能正在寻找强类型的“ViewData”属性
I think you might be searching for the strongly typed "ViewData" property