南希访问模型状态在视图中

时间:2017-01-11 12:45:22

标签: c# nancy modelstate

现在我正在使用nancy数据注释来验证模型,但是如果模型无效,我不太确定如何在视图中访问模型状态(使用超级简单视图引擎),例如:

           Post("/register", async args =>
        {
            ViewBag.ReturnUrl = Request.Query.returnUrl;
            ViewBag.LoginProviders = _signInManager.GetExternalAuthenticationSchemes().ToList();

            var model = this.BindAndValidate<RegisterViewModel>();

            if (ModelValidationResult.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var adminUsers = await _userManager.GetUsersInRoleAsync("admin");
                    if (!adminUsers.Any())
                    {
                        if (!await _roleManager.RoleExistsAsync("admin"))
                        {
                            var roleResult = await _roleManager.CreateAsync(new IdentityRole
                            {
                                Name = "admin",
                                NormalizedRoleName = "admin"
                            });

                            if (roleResult.Succeeded)
                            {
                                await _userManager.AddToRoleAsync(user, "admin");
                            }
                        }
                        else
                        {
                            await _userManager.AddToRoleAsync(user, "admin");
                        }
                    }

                    await _signInManager.SignInAsync(user, isPersistent: false);
                    Logger.LogInformation(3, "User created a new account with password.");

                    return Response.AsRedirect("~/");
                }
            }

            return View["register.html", model];
        });

如果我在验证模型后将用户返回到寄存器视图,如何在那里访问错误?目前似乎没有任何辅助方法可以输出错误,但我认为可以使用某种字典来访问视图中的错误。在南希的帖子上输出错误的标准究竟是什么?

1 个答案:

答案 0 :(得分:1)

您还需要将ModelValidationResult传递回视图,而不仅仅是model