2014-06-11 19 views
2

我有一個叫播放器型號:從下拉菜單中選擇一種模式來填充另一個模型的屬性在ASP.NET MVC

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

..而另一種模式叫做結果:

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對象。

下拉列表中填充的方法是這樣的:

@Html.LabelFor(model => model.PlayerA, new { @class = "control-label col-md-2" }) 
@Html.DropDownList("Players", "-- Select Player --") 

有人能指出我在正確的方向上如何獲得這些屬性或者在下拉列表中正確填充,或者怎麼弄Player對象正確分配給Result.PlayerA和Result.PlayerB屬性?

+0

我沒有你的完整例子。但是你需要創建你的列表項。您可能會通過創建一個添加列表項的循環來做到這一點。 –

+0

你能提供一個你想要的輸出樣本嗎?要麼返回錯誤的對象類型(Player而不是Result)或者我錯過了一些東西 – user155814

+0

當你說它們在結果對象中爲null時,你的意思是在'''''''Create'方法中? – SOfanatic

回答

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) 
相關問題