如何在不使用ViewBag的情况下绑定Identity中RegisterModel中的属性



我正在尝试通过Identity修改一些脚手架代码。

我所理解的是,它不是MVC,而是带有代码的视图。

我想将对象列表绑定到复选框列表。我可以使用ViewBag,但我更喜欢使用强类型对象,就像使用ViewModel一样。如何做到这一点?

[AllowAnonymous]
public class RegisterModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext _context;
public RegisterModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender,
RoleManager<IdentityRole> roleManager,
ApplicationDbContext context)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
_roleManager = roleManager;
_context = context;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public class InputModel
{
[Required(ErrorMessage = "Email est obligatoire")]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Mot de passe est obligatoire")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Mot de passe")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirmez le mot de passe")]
[Compare("Password", ErrorMessage = "Les 2 mots de passes ne sont pas identiques.")]
public string ConfirmPassword { get; set; }
//Profil = Role
public string Profil { get; set; }
public string NomMotif { get; set; }
public bool IsChecked { get; set; }
[BindProperty]
public List<Motif> ListMotifs { get; set; }
}
}
public void OnGet(string returnUrl = null)
{
// Do we need to instantiate this as we would do with a view model ?
InputModel inputModel = new InputModel();
ViewData["roles"] = _roleManager.Roles.ToList();
ViewData["motifs"] = _context.Motif.ToList();
inputModel.ListMotifs = _context.Motif.ToList();
ReturnUrl = returnUrl;
}

视图:

<div class="form-group">
@for (var i = 0; i < Model.Input.ListMotifs.Count;i++)
{
<div class="form-check">
<input type="checkbox" name="IsChecked_@i" asp-for="Input.ListMotifs[i].IsChecked" /> @Model.Input.ListMotifs[i].CodeMotif @Model.Input.ListMotifs[i].NomMotif <br />
</div>
}
</div>

发现问题。

我把列表从InputModel中移出,它可以

[BindProperty]
public List<Motif> ListMotifs { get; set; }
public void OnGet(string returnUrl = null)
{

ListMotifs = _context.Motif.ToList();
ReturnUrl = returnUrl;
}

@for (var i = 0; i < Model.ListMotifs.Count; i++)
{
<div class="form-check">
<input type="checkbox" name="IsChecked_@i" asp-for="ListMotifs[i].IsChecked" /> @Model.ListMotifs[i].CodeMotif @Model.ListMotifs[i].NomMotif <br />
</div>
}

相关内容

  • 没有找到相关文章

最新更新