How to set profile data for new user

4.2k views Asked by At

I have an MVC3 site and I am writing code to register a user. The code does this:

MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

The next thing it does is this:

HttpContext.Profile["FirstNAme"] = model.FirstName;
HttpContext.Profile["LastName"] = model.LastName;

This is where it fails. The error I get is:

This property cannot be set for anonymous users.

I understand why; it is because there is no user logged in or no user specified, so of course I can't set the profile for the user. I am working from page 754 onwards of Pro ASP.NET MVC 3 Framework and this is where I got this code from. I have set this up in the web.config file.

<profile enabled="true" defaultProvider="AspNetSqlProfileProvider">
  <providers>
    <clear/>
    <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
  </providers>
  <properties>
    <add name="FirstName" type="String"/>
    <add name="LastName" type="String"/>
  </properties>
</profile>

My question is how do I set the first name and last name of the user I am trying to register?

1

There are 1 answers

0
Ian Routledge On BEST ANSWER

Try getting the profile for that user's username by:

ProfileBase profile = ProfileBase.Create(model.UserName);

Yes, create 'gets' the profile for the user you just created, not just creates it (misleading!). Then you can use:

profile["FirstName"] = model.FirstName;
profile["LastName"] = model.LastName;

Don't forget to call profile.Save(); after setting the values