在 ASP.Net MVC 中设置下拉菜单的选定值
我有一个继承自 ViewModel 的 ASP.Net MVC 视图。 ViewModel 包含来自模型中两个实体的数据:
public PaginatedList<Entry> Entries { get; private set; }
public SelectList ColumnValues { get; private set; }
这两个属性用于基于列表模板的视图。 该列表循环访问条目列表并为每个条目显示一个表行。该行中的一个表格单元格内有一个 DropDownList,它由 ViewModel 的 ColumnValues 属性填充。
我可以使用以下方法获取 DropDownList 以设置其所选项目:
@Html.DropDownList("ColumnValue", Model.ColumnValues)
这将呈现页面,每一行的一个单元格中都有一个 DropDownList。但是,所选值始终设置为第一行的“ColumnValue”,并且对于所有行都是如此。
我将如何修改我的代码,以便 DropDownList 的选定值与每个单独条目的 ColumnValue 匹配。
目的是生成一种可编辑的数据网格,其中包含使用 AJAX 回发每行更改的链接。
I have an ASP.Net MVC view which inherits from a ViewModel. The ViewModel contains data from two entities in the model:
public PaginatedList<Entry> Entries { get; private set; }
public SelectList ColumnValues { get; private set; }
These two properties are used on the view, which is based on a list template.
The list iterates through the Entries list and displays a table row for each of them. Within one of the table cells in the row is a DropDownList populated from the ColumnValues propery from the ViewModel.
I can get the DropDownList to set it's selected item using the following:
@Html.DropDownList("ColumnValue", Model.ColumnValues)
This renders the page, each row with a DropDownList in one of the cells. However the selected value is always set to the 'ColumnValue' for the first row, and is like this for all of the rows.
How would I go about modifying my code so that the selected value of the DropDownList matches the ColumnValue for each inividual entry.
The aim is to produce a kind of editable datagrid with links to post back the changes per row using AJAX.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设
ViewData["ColumnValue"] = "5"
。现在,在您的ColumnValues
选择列表中,您需要有一个值为“5”的项目,它将自动被选择。例如:然后
ViewData["ColumnValue"] = "2"
会自动预选第二项。Let's suppose that
ViewData["ColumnValue"] = "5"
. Now in yourColumnValues
select list you need to have an item with the value = "5" and it will automatically be selected. For example:and then
ViewData["ColumnValue"] = "2"
will automatically preselect the second item.在视图中使用 DropDownListFor() 并将 selectList 设置为以下内容:
这似乎不是一个很好的做事方式,但它确实有效。这是现在最重要的事情。任何进一步的意见将不胜感激。
Using DropDownListFor() in the View and setting the selectList to the following works:
This doesn't seem to be a great way of doing things, but it works. And that's the most important thing right now. Any further comments would be appreciated.
您可以按照我在 为MVC4中Dropdownlist的某些记录设置Class属性,并使用“Selected”属性作为Class属性。
希望这有帮助。
You might create a custom html helper as indicated in my updated code (Updated Code - for MyDropdownListFor) on Set Class Attribute for certain records of Dropdownlist in MVC4 and use "Selected" attribute as Class attribute.
Hope this helps.