从下拉列表中选择值后获得空异常,值不能为空

时间:2019-06-06 21:46:08

标签: c# asp.net asp.net-mvc-5

我在我的registerViewModel类中添加了更多字段,其中之一是通过迁移收集的Membershiptypes,然后还修改了Accountcontroller和register.cshtml,以便可以使用下拉列表。因此,当我尝试在下拉列表中选择项目时,我收到一个null exception并且应用程序中断了,它不再创建用户了。

这是我的RegisterViewmodel。

public class RegisterViewModel{      

   public ICollection<MembershipType> MembershipTypes { get; set; }

   [Required]
   public int MembershipTypeId { get; set; }
}

这是我的get方法。

[AllowAnonymous]
public ActionResult Register()
{
    using (var db = ApplicationDbContext.Create())
    {
        RegisterViewModel newUser = new RegisterViewModel
        {
            MembershipTypes = db.MembershipTypes.ToList(),
            BirthDate = DateTime.Now
        };
            return View(newUser);
    }
}

这是我的发布方法。

if (ModelState.IsValid)
{
    var user = new ApplicationUser
        {
            UserName = model.Email,
            Email = model.Email,
            BirthDate = model.BirthDate,
            FirstName = model.FirstName,
            LastName = model.LastName,
            Phone = model.Phone,
            MembershipTypeId = model.MembershipTypeId,
            Disable = false
        };
    var result = await UserManager.CreateAsync(user, model.Password);
}

我的RegisterView就是这样。

<div class="form-group">
    @Html.LabelFor(m => m.MembershipTypeId, "MembershipTypeId", htmlAttributes: new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"),"Select List", new { @class = "form-control" })
    </div>
</div>

当我注册用户时,它应该进入数据库,但是它不会初始化result变量中的MembershipTypes,因此会引发一个异常,即值不能为null。

0 个答案:

没有答案