c# - 如何在用户配置文件中创建自定义附加字段

标签 c# asp.net-mvc asp.net-mvc-4 asp.net-membership asp.net-identity

我正在尝试创建自定义用户字段。我已经添加到注册表中了。一切正常,自动创建表,但字段 CityNULL。有人知道为什么会发生这种情况吗?

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();
            }
        }
    }
}

注册.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 添加到公共(public)类 RegisterViewModel

    [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

最佳答案

创建用户对象时需要包含 City 变量:

[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);
}

编辑:更新了代码以使用您的代码。

关于c# - 如何在用户配置文件中创建自定义附加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24384851/

相关文章:

c# - 在asp.net中选中复选框时弹出窗口

c# - 禁用 MvcSiteMapProvider 缓存

asp.net - Json.Net IsoDateTimeConverter 不工作

c# - ASP.NET MVC : Check database connectivity on application startup

asp.net-mvc - 使用带有 MVC5 属性路由的自定义路由处理程序

c# - EntityFramework 将 6.0 更新到 6.1.3 后仍然没有异步方法吗?

asp.net-mvc - 包含 System.Web.Mvc 库时 HttpGet 属性不可用

c# - 只设置单个 View 的 Culture,而不是整个程序

c# - C#2 中泛型的限制

c# - 如何在回发的文字控件中保留用户输入?