MVC5 Razor html.dropdownlistfor set 当值在数组中时被选中
问题描述
我正在使用 C# 和 .NET Framework 4.6.1 开发一个 ASP.NET MVC 5 应用程序.
I'm developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.
我有这个查看
:
ViewModel
是:
而Models.AggregationLevelConfiguration
是:
我需要在这些属性中设置选定的值:
I need to set selected value in these properties:
但我无法在 new SelectList(codeTypes, "Id", "Name");
或 new SelectList(helperCodeTypes, "Id", "Name"); 中设置它
因为选择的值在 Configurations
数组中:字段 AggregationLevelConfiguration.CodeType
和 AggregationLevelConfiguration.HelperCodeType
.
But I can't set it in new SelectList(codeTypes, "Id", "Name");
or new SelectList(helperCodeTypes, "Id", "Name");
because the selected value are in Configurations
array: fields AggregationLevelConfiguration.CodeType
and AggregationLevelConfiguration.HelperCodeType
.
我想我必须在视图中设置选定的值,但我不知道该怎么做.
I think I have to set selected value in the View, but I don't know how to do it.
如何设置选定的值?
推荐答案
不幸的是,@Html.DropDownListFor()
在循环渲染控件时的行为与其他帮助程序略有不同.这之前已在 CodePlex 上报告为问题(不确定是错误还是限制)
Unfortunately @Html.DropDownListFor()
behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)
有 2 个选项可以解决这个问题,以确保根据模型属性选择正确的选项
The are 2 option to solve this to ensure the correct option is selected based on the model property
选项 1(使用 EditorTemplate
)
为集合中的类型创建一个自定义 EditorTemplate
.在/Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml
中创建一个partial(注意名称必须与类型的名称匹配
Create a custom EditorTemplate
for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml
(note the name must match the name of the type
然后在主视图中,将 SelectList
作为 additionalViewData
and then in the main view, pass the SelectList
to the EditorTemplate
as additionalViewData
选项2(在每次迭代中生成一个新的SelectList
并设置selectedValue
)
Option 2 (generate a new SelectList
in each iteration and set the selectedValue
)
在此选项中,您的属性 CodeTypeItems
应该是 IEnumerable
,而不是 SelectList
(或者只是制作 codeTypes
一个公共财产).然后在主视图中
In this option your property CodeTypeItems
should to be IEnumerable<GenericIdNameType>
, not a SelectList
(or just make codeTypes
a public property). Then in the main view
旁注:没有必要使用 new { id = "Configurations[0].HelperCodeType"
- DropDownListFor()
方法已经生成了 id
属性
Side note: there is no need to use new { id = "Configurations[0].HelperCodeType"
- the DropDownListFor()
method already generated that id
attribute
这篇关于MVC5 Razor html.dropdownlistfor set 当值在数组中时被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!