I'm messing around while learning, trying to implement some functions of games I've played before. Now struggling where the aspect of having a button that upgrades a certain "item" in the game.
I have a view details
with a button that calls a function CallUpgradeField
inside the controller PlayersController
. The calling of the method works well. But then I want to return the same, updated view. Which is a struggle.
I get the following error:
InvalidOperationException: The model item passed into the ViewDataDictionary is of type '<>f__AnonymousType0`1[Alan.Models.Player]', but this ViewDataDictionary instance requires a model item of type 'Alan.Models.Player'.
The button (which works like it's supposed to)
@Html.ActionLink("CallUpgradeField", "CallUpgradeField", "Players",new { resourceFieldId = resourceField.ResourceFieldId }, htmlAttributes:null )
<button onclick="location.href='@Url.Action("CallUpgradeField", "Players")'" /></td>
The controller
public async Task<IActionResult> Details(int? id)
{
var players = _context.Player
.Include(villages => villages.Villages)
.ThenInclude(resourceField => resourceField.ResourceFields)
.ToList();
if (id == null || players == null)
{
return NotFound();
}
var player = players
.First(m => m.PlayerId == id);
if (player == null)
{
return NotFound();
}
var playerData = _context.PlayerData
.First(p => p.PlayerDataId == player.PlayerId);
player.PlayerData = playerData;
_context.Villages.Include(x => x.VillageData).ToList();
UpdatePlayerResources(player.Villages);
var villages = player.Villages.ToList();
var test = villages[0].ResourceFields
.FirstOrDefault(x => x.ResourceFieldId == 1);
return View(player);
}
And lastly the method
public ActionResult CallUpgradeField(int resourceFieldId)
{
ResourceField resourceField = _context.ResourceField.Single(x => x.ResourceFieldId == resourceFieldId);
Village village = _context.Villages.Single(y => y.VillageId == resourceField.VillageId);
VillageData villageData = _context.VillageData.Single(z => z.VillageDataId == village.VillageId);
var playerId = village.PlayerId;
var player = _context.Player.Single(a => a.PlayerId == playerId);
village.VillageData = villageData;
resourceField.Village = village;
resourceField.UpgradeField();
return View("Details", new { Player = player });
}
So the view error tells me the model needs an 'Alan.Models.Player'. The thing is when I debug and check the value of 'player' that's exactly what it is. I have no idea whatsoever where '<>f__AnonymousType0`1 is coming from, or how to get away from it. Google searches have led me nowhere in all honesty.
How do I pass an object into the view without making it an AnonymousType in this scenario?
CodePudding user response:
So the problem seemed to lie in the new keyword.
return View("Details", player );
Works! Thanks @Selvin for the answer.