[1/11] Become a Full Stack .NET Developer: Extending ASP.NET Identity Users
Every ASP.NET application comes with built in user authentication and authorization, thanks to ASP.NET Identity. The default signup and login forms are pretty basic, and are not suitable for real world applications that need to capture several user attributes during the signup process. This module will be focused on extending the default Signup form provided by ASP.NET Identity to allow for input of the name of the Artist for our GigHub app.
We start by deciding to replace the default Home Page provided by ASP.NET with a customized home page with a full list of Upcoming Gigs. In the HomeController.CS, we needed to retrieve all upcoming gigs on our home page from the database by placing a DBContext on the Index view. At this point in the ActionResult method we needed to eager load the list of gigs and artists by using the include method. A lambda expression was used to retrieve the artists and their associated gigs happening in the future. We finished this piece of coding by putting the model for the UpcomingGigs inside the view to be returned.
private ApplicationDbContext _context public HomeController() { _context = new ApplciationDbContext(); } public ActionResult Index() { var upcomingGigs = _context.Gigs.Include(g => g.Artist).Where(g => g.DateTime > DateTime.Now); return View(upcomingGigs); }
We then customized the Index.CSHTML to accept our Upcoming Gigs model from the Controller. We first deleted all the default content here and then wrote this code that acceptedd our mdoel from the controller and then did a for each loop through and then spat out as a list in HTML.
@model IEnumerable<GigHub.Models.Gig> @{ ViewBag.Title = "Home Page"; } <ul> @foreach (var gig in Model) { <li>@gig.DateTime - @gig.Artist.Username</li> } </ul>
As can be seen from the image posted above, the artist name is only just their email address. We need to add a name property to the IdentityUser class (which Application User inherits from) found in ApplicationUser.CS. We added a simple getter and setter for the new Name property, with a Data Annotation for both [Required] and [StringLength 100]. As we were changing our database again, a new migration was in order, followed by updating the database in our Package Manager Console to add a new Name column to our database with an empty string.
Now that we have a place to put our Artists name in our database and list it in our Upcoming Gigs, we now needed a way to capture a Artist Name on the Signup form for a user. In the Views folder under Register.CSHTML we found the view for our signup form which at the moment was only asking for email and password to signup. Not only would we need to add a new field to accept the user/artist name, we would need to modify to the AccountController.CS so that it would be able to process this new field. We needed to add the Name property to the initializer for the ApplicationUser object.