簡體   English   中英

從下拉菜單中選擇一種類型的模型,以在ASP.NET MVC中的另一種模型上填充屬性

[英]Select one type of model from a Drop Down to populate a property on another model in ASP.NET MVC

我有一個名為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屬性嗎?

您需要定義下拉列表中的項目。

 <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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM