HTML buttons are one of the most under-appreciated components of modern web forms. ASP.NET Core developers see the button
as a way to submit a form of input elements like text boxes, selects, and radio buttons. I’m here to tell you that buttons are so much more versatile. In this short post, I’ll write a simple yet fun guessing game using ASP.NET Core Razor Pages, HTML, and CSS.
The Guessing Game
At the end of this post, we will have a three by three grid of prize boxes. The user will have the option to select one, and we will reveal whether there was a prize hiding within.
When we win, we’ll see a message like this.
It’s all tears when we lose the game.
The Code
HTML buttons can hold and transmit data like any other HTML form input. Think text boxes, selects, and radio buttons. Let’s take a look at the code for our grid, and we’ll see what I mean.
<form asp-page="Index" method="post">
<div class="parent">
@for (int i = 1; i < 10; i++)
{
<div class="box @($"box{i}")">
<button
type="submit"
name="box"
value="@(i)"
>
🎁
</button>
</div>
}
</div>
</form>
A few things to note in the Razor markup:
- There is a single form element.
- There are nine HTML buttons
- Each button has the same
name
of “box” with a differentvalue
.
By clicking the specific button, we will transmit the numeric value of that button to our Razor Page.
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
[BindProperty(Name = "Box")]
public int? Box { get; set; }
public bool Winner { get; set; }
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
public void OnPost()
{
var surprise = RandomNumberGenerator.GetInt32(1, 10);
Winner = surprise == Box;
_logger
.LogInformation($"User selected Box #{Box}." +
$" User is a {(Winner ? "winner":"loser")}");
}
}
As you can see, we determine the winner by comparing the posted value with a random number generated by the RandomNumberGenerator
class.
Playing The Game
The game is straightforward; here are a few seconds of me playing it. If you want to play it too, you can clone it from my GitHub repository.
Conclusion
The HTML button
element works like any other HTML form element. It can have a name
and value
attribute, which can help developers build robust user interfaces with little to no JavaScript. In this post, we used the same name on each button, but we could have easily named each button independently. So before we reach for that JavaScript frontend framework, we should try building our UI with HTML elements. We may be surprised by the results.
Did you know buttons could do that? Let me know in the comments below.