I got my createPlayer view. It works and loads the images I got stored. And I want to choose one image in the dropdown and store that ID on my playerImageId. But both my classes (images / player) are empty in the [HttpPost] controller, when hitting the create button.
The model that is send to the view is this:
public ActionResult CreatePlayer()
{
var images = db.Image.ToList();
var playerViewModel = new PlayerViewModel(new Player(), images);
return View(playerViewModel);
}
The view looks like this:
@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>
The PlayerViewModel looks like this:
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()
{
}
}
And the CreatePlayer action looks like this:
[HttpPost]
public ActionResult CreatePlayer(PlayerViewModel playerViewModel)
{
if (ModelState.IsValid)
{
db.Player.Add(playerViewModel.Player);
db.SaveChanges();
return RedirectToAction("Teams");
}
return RedirectToAction("Teams");
}
The thing is that it works if I only sends a player to [HttpPost] CreatePlayer, like this:
[HttpPost]
public ActionResult CreatePlayer(Player player)
But in that case I don’t get the imageId.
Your view model properties only have private setters. The default model binder cannot set their values. So change your view model like this:
Also your dropdownlist is incorrect. You are attempting to bind it to a complex collection property. You need a simple scalar property to bind the selected value to:
and in the view: