【问题标题】:DropDownListFor not working with nested listDropDownListFor 不使用嵌套列表
【发布时间】:2012-11-14 11:54:22
【问题描述】:

我的 DropDownListFor 未绑定所选项目。

这是正确的模型:

public class DeliveryOrderModel
{
    public BoxInfo Boxes { get; set; }

    public class BoxInfo
    {
        public long? CountryID { get; set; }
        public IEnumerable<SelectListItem> Countries { get; set; }
    }
}

在这个模型问题中:

public class DeliveryOrderModel
{
    public List<BoxInfo> Boxes { get; set; }

    public class BoxInfo
    {
        public long? CountryID { get; set; }
        public IEnumerable<SelectListItem> Countries { get; set; }
    }
}

这是选择项

var Countries = new SelectList(new[] 
{   
    new { CountryID = 1, Text = "Name1" }, 
    new { CountryID = 2, Text = "Name2" }, 
    new { CountryID = 3, Text = "Name3" } 
} ,"CountryID","Text");

此下拉菜单适用于第一个模型:

Html.DropDownListFor(model => model.Boxes.CountryID, Model.Boxes.Countries)

这是麻烦下拉列表:

Html.DropDownListFor(model => model.Boxes[0].CountryID, Model.Boxes[0].Countries)

【问题讨论】:

  • 好的 - 现在明白了。我认为该模型可能存在问题,您需要将国家/地区列表与框信息分开。你的根模型是一个盒子和那个盒子的国家ID吗?让我知道,我可以提供一个小小的重组思路。
  • 这一步可以解决问题:(model.Countries.SingleOrDefault( v =&gt; v.Value == model.CountryID.ToString())).Selected = true;
  • 好酷。仍然认为国家列表不应该是您模型的一部分,而是一个单独的视图列表;这应该会从模型国家 ID 中自动选择国家。

标签: asp.net-mvc drop-down-menu asp.net-mvc-4 html.dropdownlistfor html-select


【解决方案1】:

首先想到 - SelectList 是一个集合,而不是一个数组,所以你可能需要这样的东西:

Html.DropDownListFor(model => model.Boxes.First().CountryID,
    Model.Boxes.First().Countries)

.First 可能还需要一个 lamda 表达式

添加

模型可能是这样的

public class DeliveryOrderModel
 {
 public List<BoxInfo> Boxes { get; set; }

 public class BoxInfo
 {
     publix Box myBox  { get; set; }
     public long? CountryID { get; set; }        
 }
}

CountryList 成为一个独立且独立的 SelectList ViewModel。 最后是视图

    Html.DropDownListFor(model => model.Boxes[0].CountryID, Countries)

或者一个 ForEach 来遍历这些盒子,或者...

好吗?

【讨论】:

  • Boxes[0] 和 Boxes.First() 之间没有区别
  • @FreeVice 见上面的补充。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
相关资源
最近更新 更多