I have been building this card game as a web application with a Gui using .NET Core. When a blank rectangle representing a playing card is clicked by the user, I would like a card object with random values to be generated (a name, a value and a suit) and for the user to be returned to the view with those values displayed on the blank card.
At the moment I have this link in my view that calls the function to generate a random card when it is clicked. But at the moment the link redirects the user to an error page with the text "This localhost page can't be found". I just wondered why this is?
The link is here:
<a asp-controller="CardController" asp-action="PlayTurn" >
This is the controller action that is supposed to generate the random card:
public IActionResult Create()
{
return View();
}
public static string GetShortName(string name)
{
string result = name.Substring(0, 1);
return result;
}
public static Card CreateCard()
{
Card[] card1 = new Card[11];
Random rnd1 = new Random();
Array suitvalues = Enum.GetValues(typeof(Suit)); // generates a random suit
Suit randomSuit = (Suit)suitvalues.GetValue(rnd1.Next(suitvalues.Length));
var i = rnd1.Next(card1.Length);
var card = new Card()
{
Suit = randomSuit,
Value = i,
DisplayName = GetShortName(randomSuit.ToString())
};
return card;
}
public IActionResult PlayTurn()
{
var card = CreateCard(); // creates a random card
TempData["CardName"] = card.DisplayName;
TempData["CardValue"] = card.Value;
TempData["CardSuit"] = card.Suit.ToString();
return Redirect("Card/Create");
}
This the the complete code for the view:
@model SnapCardGame.Models.Card
@using Microsoft.AspNetCore.Http
<div >
<h1 >Welcome to the Card Page!</h1>
@if (TempData.Peek("CardName") != null)
{
<a asp-controller="CardController" asp-action="PlayTurn" >
<ul>
<li>
@TempData.Peek("CardName")
</li>
<li>@TempData.Peek("CardValue")</li>
<li>@TempData.Peek("CardSuit")</li>
</ul>
</a>
}
else
{
<a asp-controller="Game" asp-action="PlayTurn" >
</a>
}
<a asp-controller="Game" asp-action="PlayTurn" >
</a>
</div>
I'd like to pass the randomly generated values to the view via Temp Data. At the moment though, I just get the resulting page:
If anyone has any suggestions, please feel free to let me know?
Thanks,
Robert Young
London, UK
CodePudding user response:
Change your link to:
<a asp-controller="Card" asp-action="PlayTurn" >
The corresponding controller name should be Card
, not CardController
.