从下拉列表中选择一种类型的模型来填充ASP中另一种模型的属性.净MVC
本文关键字:模型 填充 ASP 属性 MVC 另一种 类型 选择 下拉列表 一种 | 更新日期: 2023-09-27 18:08:06
我有一个模型叫做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();
}
但是,当我想添加一个新的结果并从视图上的下拉列表中选择两个球员的名字时,结果对象上的这些Player属性为空。我希望它们包含Player对象。
下拉列表的填充方式如下:
@Html.LabelFor(model => model.PlayerA, new { @class = "control-label col-md-2" })
@Html.DropDownList("Players", "-- Select Player --")
有人能指出我在正确的方向上如何获得这些属性要么在下拉列表中正确填充,或者如何获得玩家对象正确分配给结果。PlayerA和Result。PlayerB属性呢?
您需要定义下拉列表的项。
<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)