Create Membership Profile MVC 3
-
09-12-2019 - |
Question
I'm creating an Admin page for my ASP.Net MVC 3 application. I can create a new user, like this:
MembershipUser mu = Membership.CreateUser(user.UserName, user.Password);
Membership.UpdateUser(mu);
I can assign roles like this:
Roles.AddUserToRole(user.UserName, "Customer");
But how do I create and attach a new profile?
ProfileManager
has methods to Find and Delete profiles, but no method to create one.
If it matters, I have added custom profile properties like this:
<properties>
<add name="FirstName" />
<add name="LastName" />
</properties>
I assume that a profile is not automatically created when the user is created, because a subsequent call to
ProfileInfoCollection profiles =
ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
returns an empty collection, while Membership.GetAllUsers()
returns the one user I just created.
Solution
I just realized that I have to use ProfileBase
to create a new profile entry:
ProfileBase pi = ProfileBase.Create(user.UserName);
OTHER TIPS
you can access the profile properties using the HttpContext.Profile property, which is available through the Controller class:
ViewBag.Name = HttpContext.Profile["Name"];
The ASP.NET framework uses the profile provider to load the profile properties for a user the first time we access the profile data and writes any modifications back through the provider at the end of the request. We don’t have to explicitly save changes; it happens automatically.