视图模型未在 MVC 5 中将值从寄存器操作传递到异步寄存器操作



我目前正在自定义注册页面以在注册期间传入公司 ID。我对 MVC 最佳实践相当陌生,所以如果这不是最理想的方法,请告诉我。我已经修改了标识模型以适应 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 表达式正确抓取了正确的公司 ID。它无法将视图模型传递给异步注册控制器。

由于它无法从其他注册操作传递视图模型,因此无法分配公司 ID 并引发外键错误。

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

任何建议都值得赞赏

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

Register.cshtml,添加:

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

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

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

最新更新