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
。