我得到了我的 createPlayer 视图。它可以工作并加载我存储的图像。我想在下拉列表中选择一个图像并将该 ID 存储在我的 playerImageId 中。[HttpPost]
但是当我点击创建按钮时,我的两个类(图像/播放器)在控制器中都是空的。
发送到视图的模型是这样的:
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
.