为视图中的项目创建 DropDownList
我想创建一个具有模型数据之一绑定的 DropDownList,但我希望在视图中构建下拉项,并且我不希望这些项出现在模型数据中或来自我的控制器。您能否建议如何在视图中构建选择列表 基本上我想创建这样的东西:
<%= Html.DropDownListFor(model=>model.SomeProperty,<<create the dropdown list items here>> %>
请提出建议。
-桑帕特。
I want to create a DropDownList with a binding for one of my model data, but i want the dropdown items to be built within the View and i do not want the items coming in the Model data or from my controller. Can you please suggest how to build the selectlist within View
Basically I want to create something like this:
<%= Html.DropDownListFor(model=>model.SomeProperty,<<create the dropdown list items here>> %>
Please suggest.
-Sampat.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能那样使用它。顾名思义,它用于为对象中的每个属性返回一个 HTML 选择元素,该对象由使用指定列表项和 HTML 属性的指定表达式表示。
尽管您可以在视图中创建此列表对象,如下所示:-
更新
我将以带有 Id/Name 对的国家/地区模型为例。现在
,在控制器操作中,您可以将其作为选择列表传递:
最后在视图中,您可以按以下方式使用 DropDownListFor。
在 Sidenote 中,如果您只想显示具有值的数字列表,您可以直接输入 HTML 并使用它,而不是使用 DropDownListFor。就像下面一样,
只需确保“yourModelPropertyName”正确,并且它应该是您想要更新的属性的名称
更多更新
在您不想显示所选值的视图中,请使用以下内容代码
这应该可以解决问题:-)
You can't use it that way. As the name suggests its for returning an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes.
Though you can create this list object in view like following :-
Update
I will take the example of a Country Model with an Id/Name pair. Like following
Now, in your controller action, you can pass it as a selectlist:
And finally in View, you can use the DropDownListFor in the following manner.
On a Sidenote, if you just want to display a list of numbers with value, you can directly enter the HTML and utilize it, rather than using the DropDownListFor. Like follwing
Just make sure that "yourModelPropertyName" is correct and it should be the one for the property where you want it updated
More update
In the views where you wan't to show the selected value, use below code
This shall do the trick :-)
@Pankaj 给了你一个粗略的方法。您还可以将
SelectListItem
对象 tobject 的IEnumerable
从控制器传递到您的视图,并基于该对象创建您的选择元素。这是一个很好的例子:
在 ASP.NET MVC 中使用 Html 选择元素(又名 DropDownList)的方法
想象一下您的控制器看起来像像这样的东西:
在你看来,
DropDownListFor
html helper应该看起来像这样:@Pankaj gave you a rough way of doing it. You can also pass the
IEnumerable
ofSelectListItem
object tobject to your view from controller and create your select element based on that.Here is a good example:
A Way of Working with Html Select Element (AKA DropDownList) In ASP.NET MVC
Imagine that your controller looks like something like this:
on your view,
DropDownListFor
html helper should look like something like this: