DropDownListFor不使用嵌套列表

时间:2012-11-14 11:54:23

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

我的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; }
    }
}

这是SelectItems

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)

1 个答案:

答案 0 :(得分:0)

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

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

也可能需要.First

的lamda expresson

<强> ADDITION

模型可能就像

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迭代框,或......

OK?