0

在此处输入图像描述

我正在尝试将数据加载到嵌套母版页中的下拉列表中,但视图中的模型始终为空。我怎样才能做到这一点?

在模型中

 public class AllInOneModel
{
    public string City { get; set; }
    public IEnumerable<City> cities { get; set; }

}

在控制器中

public ActionResult Add()
    {
        return View(new AllInOneModel());
    }

在视图中

@model  IBilik.Models.AllInOneModel
@Html.DropDownListFor(model => model.City,(SelectList)Model.cities)
4

1 回答 1

0

就我个人而言,我会跳过“AllInOneModel”并坚持将单个城市发送到视图中。

控制器动作可能看起来有点像这样。

public ActionResult Index()
{
    //TODO: get current cities from database
    List<City> cities = new List<City>
    {
        new City { CityID = 1, CityName = "City1" },
        new City { CityID = 2, CityName = "City2" },
        new City { CityID = 3, CityName = "City3" }
    };

    // Create the list of selectlistitems to populate the dropdown
    List<SelectListItem> listItems = new List<SelectListItem>();
    foreach(var c in cities)
    {
        listItems.Add(new SelectListItem { Value = c.CityID.ToString(), Text = c.CityName });
    }

    //Throw them into viewbag
    ViewBag.ListItems = listItems;

    //TODO get some city (perhaps from db) to send to view
    var city = new City { CityID = 1, CityName = "City1" };  

    return View(city);
}

然后你会以这种方式渲染视图。

@model IBilik.Models.City

@Html.DropDownListFor(model => model.CityID, ViewBag.ListItems as List<SelectListItem>)
于 2018-03-25T11:28:28.470 回答