使用 Html.DropDownListFor() 不使用模型
我将一个模型传递到我的视图 (.net mvc 3) 中,该模型无法包含我想要用来填充下拉列表的信息。
我从未使用过 Html.DropDownListFor() 但一直只使用 Html.DropDownList()。我想在我的技巧包中添加另一个工具,因此想尝试合并 Html.DropDownListFor()。
是否可以将此助手与 ViewBag 变量中设置的键/值对一起使用?
请告知,任何代码示例将不胜感激(前端(剃刀)和后端(控制器上))。
TIA
I'm passing a Model into my view (.net mvc 3) that can't contain the information that I want to use to populate my drop down list.
I've never used Html.DropDownListFor() but have always just used Html.DropDownList(). I want to add another tool to my bag of tricks though and so want to try and incorporate Html.DropDownListFor().
Is it possible to use this helper with Key/Value pair set in a ViewBag variable?
Please advise, any code samples would be greatly appreciated (both front end (razor) and back end (on controller)).
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
绝对不是。如果您想使用强类型帮助程序(例如 Html.DropDownListFor),您需要一个视图模型。由于我总是建议使用视图模型,因此这里有一个示例:
正如您在此示例视图模型中所看到的,对于每个下拉列表,您需要 2 个属性:一个用于保存所选值的标量属性和一个
SelectListItem< 的集合/code> 将保存选项,其中每个选项由值和文本组成。
然后控制器负责初始化此视图模型并将其传递给视图:
然后您将拥有此视图模型对应的强类型视图,您将能够在其中使用强类型版本的助手:
以下句子从你的问题中值得关注:
您不应该将模型传递给视图。您应该传递一个视图模型。视图模型是您为每个视图专门定义的类。它将包含该视图所需的必要信息。因此,单个视图模型可以由多个模型组成,因为这是视图的要求。
Absolutely not. If you want to use strongly typed helpers such as Html.DropDownListFor you need a view model. And since I always recommend using a view model, here's an example:
As you can see in this sample view model, for each dropdown you need 2 properties: a scalar property that will hold the selected value and a collection of
SelectListItem
that will hold the options where each option consists of a value and text.Then it's the controller's responsibility to initialize this view model and pass it to the view:
and then you will have a corresponding strongly typed view to this view model in which you will be able to use the strongly typed version of the helpers:
The following sentence from your question deserves some attention:
You should not be passing a model to a view. You should be passing a view model. A view model is a class that you specifically define for each view. It will contain the necessary information that this view will require. So a single view model could be composed from multiple models simply because such are the requirements of your view.