使用额外的属性更新AspNetUsers无效

时间:2018-10-19 16:12:18

标签: c# asp.net asp.net-mvc razor model-view-controller

晚安。我被困在似乎无法修复自己的事情上。我在项目中创建了一个名为Address.cshtml.cs(模型)和Address.cshtml(视图)的剃须刀页面,以使用户能够注册后添加他们的用户信息。 var result = await _userManager.UpdateAsync(user);似乎不起作用。我尝试了两种更新数据库中的方法的方法:

第一次尝试

  [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> AccountChange(UserModel model)
        {
            if (ModelState.IsValid)
            {

                // Get the current application user
                var user = await _userManager.GetUserAsync(User);

                //Update the details
                user.name = model.name;
                user.surname = model.surname;
                user.street = model.street;
                user.streetnumber = model.streetnumber;
                user.city = model.city;
                user.zipcode = model.zipcode;

                // Update user address
                var result = await _userManager.UpdateAsync(user);
            }


            //await _signInManager.RefreshSignInAsync(User);
            _logger.LogInformation("User added their address information successfully.");
            StatusMessage = "Your address information has been added.";

            return RedirectToPage();

        }
    }

第二次尝试

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(UserModel model)
{
    if (ModelState.IsValid)
    {
        UserModel u = await _userManager.FindByIdAsync(model.Id);
        u.name = model.name;
        u.surname = model.surname;
        u.street = model.street;
        u.streetnumber = model.streetnumber;
        u.city = model.city;
        u.zipcode = model.zipcode;
        await _userManager.UpdateAsync(u);
        return RedirectToAction("Index");
    }
    return RedirectToPage();
}

如何解决此问题?我在下面添加了所有必需的代码。

Address.cshtml.cs

namespace bytme.Areas.Identity.Pages.Account.Manage
{
    public class AddressModel : PageModel
    {
        private readonly UserManager<UserModel> _userManager;
        private readonly SignInManager<UserModel> _signInManager;
        private readonly ILogger<AddressModel> _logger;

        public AddressModel(
            UserManager<UserModel> userManager,
            SignInManager<UserModel> signInManager,
            ILogger<AddressModel> logger)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public string ReturnUrl { get; set; }

        [TempData]
        public string StatusMessage { get; set; }

        public class InputModel
        {
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Name")]
            [StringLength(100, ErrorMessage = "Invalid input. Maximum is 100 characters.")]
            public string name { get; set; }

            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Surname")]
            [StringLength(100, ErrorMessage = "Invalid input. Maximum is 100 characters.")]
            public string surname { get; set; }

            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Street")]
            [StringLength(48, ErrorMessage = "The longest street name in the Netherlands is 48 characters.")]
            public string street { get; set; }

            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "House Number")]
            [StringLength(5, ErrorMessage = "The longest house number in the Netherlands is 5 characters.")]
            public string streetnumber { get; set; }

            //[DataType(DataType.Text)]
            //[Display(Name = "House Number Addition", Description = "For example A or II")]
            //[StringLength(6, ErrorMessage = "
            //public string streetnumberadd { get; set; }

            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "City")]
            [StringLength(28, ErrorMessage = "The longest place name in the Netherlands is 28 characters.")]
            public string city { get; set; }

            [Required]
            [DataType(DataType.PostalCode)]
            [Display(Name = "Postal Code")]
            [RegularExpression(@"^[1-9][0-9]{3}\s?[a-zA-Z]{2}$", ErrorMessage = "Invalid zip, for example: 1234AB")]
            public string zipcode { get; set; }
        }

        public void OnGet(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> AccountChange(UserModel model)
        {
            if (ModelState.IsValid)
            {

                // Get the current application user
                var user = await _userManager.GetUserAsync(User);

                //Update the details
                user.name = model.name;
                user.surname = model.surname;
                user.street = model.street;
                user.streetnumber = model.streetnumber;
                user.city = model.city;
                user.zipcode = model.zipcode;

                // Update user address
                var result = await _userManager.UpdateAsync(user);
            }


            //await _signInManager.RefreshSignInAsync(User);
            _logger.LogInformation("User added their address information successfully.");
            StatusMessage = "Your address information has been added.";

            return RedirectToPage();

        }
    }
}

Address.cshtml

@page
@model AddressModel
@inject SignInManager<UserModel> SignInManager
@using Microsoft.AspNetCore.Identity
@using bytme.Models;
@{
    ViewData["Title"] = "Add Address Information";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.Partial("_StatusMessage", Model.StatusMessage)
@{
    var hasExternalLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()).Any();
}
<div>
    <h3>Change your account settings</h3>
    <hr />
    <div class="row">
        <div class="col-md-3">
            <partial name="_ManageNav" />
        </div>
        <div class="col-md-9">
            <div class="row">
                <div class="col-md-6">
                    <h4>@ViewData["Title"]</h4>
                    <form id="change-password-form" method="post">
                        <div asp-validation-summary="All" class="text-danger"></div>
                        <div class="form-group">
                            <label asp-for="Input.name"></label>
                            <input asp-for="Input.name" class="form-control" />
                            <span asp-validation-for="Input.name" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="Input.surname"></label>
                            <input asp-for="Input.surname" class="form-control" />
                            <span asp-validation-for="Input.surname" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="Input.street"></label>
                            <input asp-for="Input.street" class="form-control" />
                            <span asp-validation-for="Input.street" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="Input.streetnumber"></label>
                            <input asp-for="Input.streetnumber" class="form-control" />
                            <span asp-validation-for="Input.streetnumber" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="Input.city"></label>
                            <input asp-for="Input.city" class="form-control" />
                            <span asp-validation-for="Input.city" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="Input.zipcode"></label>
                            <input asp-for="Input.zipcode" class="form-control" />
                            <span asp-validation-for="Input.zipcode" class="text-danger"></span>
                        </div>
                        <button type="submit" class="btn btn-default">Submit</button>
                    </form>
                </div>
            </div>

        </div>
    </div>
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

UserModel.cs

namespace bytme.Models
{
    public class UserModel : IdentityUser
    {
        public override string Id { get; set; }
        public override string Email { get; set; }
        public override string UserName { get; set; }
        public override string PasswordHash { get; set; }
        public string zipcode { get; set; }
        public string city { get; set; }
        public string street { get; set; }
        public string streetnumber { get; set; }
        public string name { get; set; }
        public string surname { get; set; }
    }
}

ApplicationDbContext.cs

namespace bytme.Data
{
    public class ApplicationDbContext : IdentityDbContext<UserModel>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }

        public DbSet<bytme.Models.Item> Items { get; set; }
        public DbSet<bytme.Models.ItemCategories> ItemCategories { get; set; }
        public DbSet<bytme.Models.UserModel> UserModels { get; set; }
        public DbSet<bytme.Models.OrderHistory> OrderHistories { get; set; }
        public DbSet<bytme.Models.OrderMain> OrderMains { get; set; }
        public DbSet<bytme.Models.OrderStatus> OrderStatuses { get; set; }
        public DbSet<bytme.Models.WishlistModel> WishlistModels { get; set; }
        public DbSet<bytme.Models.ShoppingCartModel> ShoppingCartModels { get; set; }
    }
}

1 个答案:

答案 0 :(得分:1)

检查代码后,我发现了几个问题。

1。。我对您的发帖方法AccountChange表示怀疑。应遵循以下约定。根据Microsoft有关剃须刀页面的文档,生成了一些默认的方法处理程序,例如:OnGet OnPost OnGetAsync OnPostAsync等。

如果您想使用自定义处理程序名称,它也必须遵循一些命名约定。

  

方法应以   OnPost[Get,...]<Handlername>[Async|NoAsync](its optional)

     

因此,您的方法应命名为OnPostAccountChangeAsync()

如果定义了这样的方法,则必须告诉视图您要使用指定的处理程序。您使用asp-page-handler指令告诉它,因此您的表单应如下所示:

<form id="change-password-form" method="post">
   //...
   <button type="submit" class="btn btn-default" asp-page-handler="AccountChange">Submit</button>
</form>


2。。您正在绑定属性Input

[BindProperty]
public InputModel Input { get; set; }

但是,在方法OnPostAccountChangeAsync()中,您尝试访问类型为UserModel的参数实例,该实例将为空。它没有绑定。在良好的情况下,您将获得null异常。在糟糕的情况下,您将使用空属性更新实体。因此,您的方法OnPostAccountChangeAsync()应该在InputModel的参数实例处接受,或者您可以直接在方法主体内部访问此属性(可以摆脱参数)

OnPostAccountChangeAsync(InputModel Input)
{
 //...
}


3。,这是次要的事情,它提高了代码的可读性。请在变量命名方面保持一致。一致性使代码的方向更好。在Csharp中,属性应以大写字母(PascalCasing)开头。不要犹豫,请检查C# naming convention


在评论部分中有关UserManager的问题:
您可以将Identity视为包装器(而不是api),该包装器除了提供其他功能外,还为用户管理提供了有用的方法。如我所说,如果您查看软件包的依赖性,可以发现Entity Framework是在Identity nuget软件包中提供的。这是什么意思?它使您有可能不仅仅依赖于某些“神秘的” Identity。您可以明确地使用Entity Framework例如将新用户保存到表AspNetUsers中。明确地说,您不受限制。但是,如果您已经使用了Identity,则最好使用其可用方法。