Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-membershipasp.net-identity

How to create custom additional fields in UserProfile


I'm trying to create a custom user fields. I've added to the registration form. Everything works properly, automatically creates the table but the field City is NULL. Anyone know why this happens?

public class ApplicationUser : IdentityUser
{
    public string City { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    static ApplicationDbContext()
    {
        Database.SetInitializer(new MySqlInitializer());
    }
    public ApplicationDbContext() : base("MySql.Data.MySqlClient")
    {
    }
}

MySqlInitializer.cs

public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
    public void InitializeDatabase(ApplicationDbContext context)
    {
        if (!context.Database.Exists())
        {
            context.Database.Create();
        }
        else
        {
            var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
            string.Format(
              "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
              "[users]"));

            if (migrationHistoryTableExists.FirstOrDefault() == 0)
            {
                context.Database.Delete();
                context.Database.Create();
            }
        }
    }
}

Register.cshtml

<div class="form-group">
    @Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.City, new { @class = "form-control" })
    </div>
</div>

AccountViewModels.cs in public class RegisterViewModel added

    [Required]
    [Display(Name = "City")]
    public string City { get; set; }

AccountController.cs

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

null


Solution

  • You need to include the City variable when you create the user object:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName, City = model.City  };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    }
    

    EDIT: Updated code to use your code.