2012-04-23 84 views
1

我得到了我的createPlayer視圖。它工作並加載我存儲的圖像。我想在下拉列表中選擇一張圖片並將該ID存儲在我的playerImageId中。但是當按下創建按鈕時,[HttpPost]控制器中的兩個類(圖像/播放器)都是空的。創建對象時,我的類在viewModel中爲空/空。 MVC,EF

模型,在發送給看法是這樣的:

public ActionResult CreatePlayer() 
{ 
    var images = db.Image.ToList(); 
    var playerViewModel = new PlayerViewModel(new Player(), images); 
    return View(playerViewModel); 
} 

的看法是這樣的:

@model MariedalsIK.Models.PlayerViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>Player</legend> 
     <div> 
      @Html.LabelFor(model => model.Image) 
     </div> 
     <div> 
      @Html.DropDownListFor(model => model.Image, Model.Image.Select(x => new SelectListItem 
                       { 
                        Text = x.ImageName, 
                        Value = x.Id.ToString() 
                       })) 
     </div> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.Player.Name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Player.Name) 
      @Html.ValidationMessageFor(model => model.Player.Name) 
     </div> 

的PlayerViewModel看起來是這樣的:

public class PlayerViewModel 
    { 
     public PlayerViewModel(Player player, IEnumerable<Image> images) 
     { 
      Player = player; 
      Image = images; 
     } 

     public Player Player { get; private set; } 
     public IEnumerable<Image> Image { get; private set; } 

     public PlayerViewModel() 
     { 

     } 
    } 

而CreatePlayer動作如下所示:

[HttpPost] 
public ActionResult CreatePlayer(PlayerViewModel playerViewModel) 
{ 
    if (ModelState.IsValid) 
    { 
     db.Player.Add(playerViewModel.Player); 
     db.SaveChanges(); 
     return RedirectToAction("Teams"); 
    } 
    return RedirectToAction("Teams"); 
} 

的事情是,它的工作原理,如果我只向玩家[HttpPost]的createPlayer,像這樣:

[HttpPost] 
public ActionResult CreatePlayer(Player player) 

但在這種情況下,我沒有得到imageId

回答

2

您的視圖模型屬性只有私人設置者。默認的模型聯編程序不能設置它們的值。所以改變你的視圖模型是這樣的:

public class PlayerViewModel 
{ 
    public Player Player { get; set; } 
    public IEnumerable<Image> Image { get; set; } 
} 

此外,您的下拉列表不正確。您正試圖將其綁定到一個複雜的集合屬性。你需要一個簡單的標量屬性選擇的值綁定到:

public class PlayerViewModel 
{ 
    public Player Player { get; set; } 

    public IEnumerable<Image> Images { get; set; } 
    public string ImageId { get; set; } 
} 

,並在視圖:

<div> 
    @Html.LabelFor(x => x.ImageId) 
</div> 
<div> 
    @Html.DropDownListFor(
     x => x.ImageId, 
     new SelectList(Model.Images, "Id", "ImageName") 
    ) 
</div>