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.
我有这个查看:
@model MyProject.Web.API.Models.AggregationLevelConfViewModel
[...]
@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
ViewModel 是:
public class AggregationLevelConfViewModel
{
    private readonly List<GenericIdNameType> codeTypes;
    private readonly List<GenericIdNameType> helperCodeTypes;
    public IEnumerable<SelectListItem> CodeTypeItems
    {
        get { return new SelectList(codeTypes, "Id", "Name"); }
    }
    public IEnumerable<SelectListItem> HelperCodeTypeItems
    {
        get { return new SelectList(helperCodeTypes, "Id", "Name"); }
    }
    public int ProductionOrderId { get; set; }
    public string ProductionOrderName { get; set; }
    public IList<Models.AggregationLevelConfiguration> Configurations { get; set; }
    public AggregationLevelConfViewModel()
    {
        // Load CodeTypes to show it as a DropDownList
        byte[] values = (byte[])Enum.GetValues(typeof(CodeTypes));
        codeTypes = new List<GenericIdNameType>();
        helperCodeTypes = new List<GenericIdNameType>();
        for (int i = 0; i < values.Length; i++)
        {
            GenericIdNameType cType = new GenericIdNameType()
            {
                Id = values[i].ToString(),
                Name = EnumHelper.GetDescription((CodeTypes)values[i])
            };
            if (((CodeTypes)values[i]) != CodeTypes.NotUsed)
                codeTypes.Add(cType);
            helperCodeTypes.Add(cType);
        }
    }
}
而Models.AggregationLevelConfiguration是:
public class AggregationLevelConfiguration
{
    public byte AggregationLevelConfigurationId { get; set; }
    public int ProductionOrderId { get; set; }
    public string Name { get; set; }
    public byte CodeType { get; set; }
    public byte HelperCodeType { get; set; }
    public int PkgRatio { get; set; }
    public int RemainingCodes { get; set; }
}
我需要在这些属性中设置选定的值:
I need to set selected value in these properties:
public IEnumerable<SelectListItem> CodeTypeItems
{
    get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
    get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
但我无法在 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
@model yourAssembly.AggregationLevelConfiguration
@Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
然后在主视图中,将 SelectList 作为 additionalViewData
and then in the main view, pass the SelectList to the EditorTemplate as additionalViewData
@using (Html.BeginForm())
{
  ...
  @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
  ...
选项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
@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
旁注:没有必要使用 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 当值在数组中时被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
