我有一个名为Player的模型:
public class Player
{
public int ID { get; set; }
public string Name { get; set; }
public int Wins { get; set; }
public int Draws { get; set; }
public int Losses { get; set; }
public int League { get; set; }
[Display(Name="GF")]
public int GoalsFor { get; set; }
[Display(Name="GA")]
public int GoalsAgainst { get; set; }
public int Points
{
get { return Wins * 3 + Draws; }
}
}
..和另一个名为Result的模型:
public class Result
{
public int ID { get; set; }
public Player Winner { get; set; }
public Player Loser { get; set; }
public bool Draw { get; set; }
[Display(Name="Player A")]
public Player PlayerA { get; set; }
[Display(Name = "Player B")]
public Player PlayerB { get; set; }
[Display(Name = "Player A Goals")]
public int PlayerAGoals { get; set; }
[Display(Name = "Player B Goals")]
public int PlayerBGoals { get; set; }
}
当我想创建一个新结果时,播放器列表被添加到控制器中的ViewBag并传递给视图:
public ActionResult Create()
{
IEnumerable<Player> players = db.Players.ToList();
ViewBag.Players = new SelectList(players, "Name", "Name");
return View();
}
但是,当我想添加新结果并从视图的下拉列表中选择两个玩家的名称时,Result对象上的这些Player属性为null。我希望他们能包含Player对象。
填充下拉列表的方式如下:
@Html.LabelFor(model => model.PlayerA, new { @class = "control-label col-md-2" })
@Html.DropDownList("Players", "-- Select Player --")
有人可以指出我如何在下拉列表中正确填充这些属性,或者如何将Player对象正确分配给Result.PlayerA和Result.PlayerB属性?
答案 0 :(得分:0)
您需要定义下拉列表中的项目。
<div class="editor-field">
@{
List<SelectListItem> items = new List<SelectListItem>();
//You may want to loop to generate your items.
items.Add(new SelectListItem
{
//Or you code that generates your SelectListItems
Text = "Your_Text_1",
Value = "Your Value_1",
});
items.Add(new SelectListItem
{
//Or you code that generates your SelectListItems
Text = "Your_Text_2",
Value = "Your_Value_2",
});
}
@Html.DropDownListFor(model => model.PlayerA, items)
@Html.ValidationMessageFor(model => model.PlayerA)