Tuesday, January 30, 2018

Adding to, and Accessing, Properties on the ApplicationUser Class in ASP.Net Core 2.0 MVC

Ok, this is actually really simple to do, but frack me if it didn't take me awhile to figure things out.  Note for this example we will use a code first approach just to show the concept.

Step 0: Create a new core MVC project, select the option for authentication called something like "store credentials in application" (I'm updating VS Studio right now so going on memory).

Step 1: Add whatever properties you want to the ApplicationUser class, stuff like

public string SomeField {get; set;}
public string SomeOtherField {get;set}

Save

Step 2: from the nuget console, run add-migration , give it a name.

Step 3: from the nuget console, run update-database

When done you can use whatever to see the table with the new fields (In VS sql server object explorer).

Optional: You can tweak all the view and manage models to support your new fields.  I didn't for now.  I just went in and gave one of my new fields a value.

Step 4: Tweak you controller and inject the usermanager into your controller.
 
a) include using Microsoft.AspNetCore.Identity; and maybe the namespace of where you models reside.

b) Add a private usermanager variable to your controller like so-

    private readonly UserManager _userManager;

c) Then on your initialization method, inject the usermanager.  If your controller is names HomeController it would look like this-

public HomeController ( UserManager userManager )
    {
      _userManager = userManager;
    }

Step 5: In your controller you can now access the added properties to your user like so (in this example I added PersWeboptionsText to the field  ApplicationUser class.

  // test for a given value...
      var weboption = _userManager.GetUserAsync( User ).Result?.PersWeboptionsText;


YAY!  Now you can use and abuse that value to do whatever.


But what about in a view?  Are we stuck always passing that value in as ViewData or something?  No, you can use a similar approach.  You must inject the user manager into your view (or into your _layout.cshtml file at the top like of the view like so-

@inject UserManager UserManager


Ok, now in your page to access customer ApplicationUser properties/fields, again using PersWeboptionsText as an example field added to ApplicationUser, you can do so like this-

@UserManager.GetUserAsync( User ).Result?.PersWeboptionsText


That should get you going.  Next up is adding collections to the ApplicationUser and making sure they populate right.

I should come back and reformat this post and make it pretty...ain't nobody got time for that.

Happy Coding.