I have a problem.
If you read my last letter, you might recall I used Entity Framework to save a lot of time scaffolding my Controllers and Views for the Genres and Uploads Models for my ToonSpace application.
But I signed my last letter with a minor bug:
My GenreId dropdown (which should just display "Genre", but I'll get to that later) displays blank. This isn't a big deal though, as it's simply a result of Entity Framework trying to anticipate the purpose of that field. But it isn't functional.
I want to provide the user with a pre-populated list of options for the Genre of their uploaded webtoons, and I achieve this with enums.
I first create a new folder on the top level of my project in the Solutions Explorer called "enums" and add a new class to it called GenreName.
The enum type is essentially a comma-separated list of strings, zero-indexed, and alphanumerical. I use the indexed property of my enum to function as the GenreId for each Upload object.
I declare it as a public enum instead of a class and create five options for a user to choose from.
Next I add GenreName as a property of my upload Model, making sure to a using directive for GenreName in my using directives above.
I make some small changes to my Create and Edit Views in the Uploads View folder, changing all instances of GenreId to GenreNames and amending the asp-items property to connect it to my enum.
<div class="form-group"> <label asp-for="GenreName" class="control-label"></label> <select asp-for="GenreName" class ="form-control" asp-items="Html.GetEnumSelectList<GenreName>()"></select> </div>
I make sure to add a using directive to bring in my Enums folder as well.
Before building the solution, I migrate my changes to the database and update it.
Finally, I build the solution and check that my new dropdown menu works.
If you're like me, dear Coder, you might find the Pascal case of GenreName and SciFi in the dropdown to be off-putting from the end user's perspective.
We can fix these cosmetic issues by leveraging Data Annotations.
Though enums are alphanumerical, I can still use a hyphen within a data annotation to display the enum's value in the View. I simply add this using directive:
and this display text above the index of my desired value:
[Display(Name = "Sci-Fi")] SciFi,
I simply use the same using directive and display syntax in my Upload model to clean up the Genre Name tag.
Finally, our bugs are fixed and the data displays nicely for the end user.
I hope my letters are finding you well, dearest Coder, and I look forward to your swift replies.
Until then, godspeed in your keystrokes.