ViewModel没有将值从Register Action传递到MVC 5中的Async Register Action

时间:2018-04-16 02:24:27

标签: asp.net asp.net-mvc

我目前正在自定义注册页面,以便在注册期间传入companyID。我对MVC最佳实践相当新,所以如果这不是最理想的方法,请告诉我。我已经修改了IdentityModel以容纳CompanyID属性。

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    public Company Company { get; set; }
    public int CompanyId { get; set; }
}

目前我正在修改默认注册页面作为测试。

观察到的行为:正在通过lambda表达式正确获取正确的CompanyID。它无法将viewModel传递给async RegisterController。

由于它无法从其他Register操作传递viewModel,因此无法分配CompanyID并引发外键错误。

   // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        var viewModel = new RegisterViewModel
        {
            CompanyID = _context.Companies.First(c => c.CompanyName == "Company2").Id
        };
        return View("Register", viewModel);
    }


   // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, CompanyId = model.CompanyID };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {



                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

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

赞赏任何建议

1 个答案:

答案 0 :(得分:2)

您应该在视图中为公司ID添加字段。

Register.cshtml中,添加:

<input type="hidden" name="CompanyId" value="@Model.CompanyId" />

或者,使用内置的HTML帮助器:

@Html.HiddenFor(m => m.CompanyId)