如何处理 传递到字典中的模型项是 LoginViewModel 类型,但此字典需要 RegisterViewModel

本文关键字:字典 LoginViewModel 类型 RegisterViewModel 模型 处理 何处理 | 更新日期: 2023-09-27 18:32:44

伙计们,我遇到了一个问题,无法找到解决方案。我正在使用 ASP.Net MVC5 标识。出于某些特定原因,我使用 Html.RenderPartial 将寄存器视图添加到我的登录视图中。这是我的控制器。

[AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }
[AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }
        //
        // 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 };
                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 http://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);
        }

下面是我的登录视图。

@using EShopperTheme.Models
@using Microsoft.AspNet.Identity
@model LoginViewModel
<section id="form">
        <!--form-->
        <div class="container">
            <div class="row">
                <div class="col-sm-4 col-sm-offset-1">
                    <div class="login-form">
                        <!--login form-->
                        <h2>Login to your account</h2>
                        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                        {
                            @Html.AntiForgeryToken()
                            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                            <div>
                                <div>
                                    <input data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Email" name="Email" type="text" value="" placeholder="Email" />
                                    @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div>
                                <div>
                                    <input data-val="true" data-val-required="The Password field is required." id="Password" name="Password" type="password" placeholder="Password" />
                                    @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <span>
                                @Html.CheckBoxFor(m => m.RememberMe)
                                Keep me signed in
                            </span>
                            <div>
                                <div>
                                    <button type="submit" class="btn btn-default">Login</button>
                                </div>
                            </div>
                            @* Enable this once you have account confirmation enabled for password reset functionality
                                <p>
                                    @Html.ActionLink("Forgot your password?", "ForgotPassword")
                                </p>*@
                        }
                    </div><!--/login form-->
                </div>
                <div class="col-sm-1">
                    <h2 class="or">OR</h2>
                </div>
                <div class="col-sm-4">
                    <div class="signup-form">
                        <!--sign up form-->
                        <h2>New User Registration!</h2>
                    **@{ Html.RenderPartial("_RegisterPartial");}**
                    </div><!--/sign up form-->
                </div>
            </div>
        </div>
    </section><!--/form-->

如您所见,我已经在顶部添加了登录视图模型,这是我_RegisterPartial视图。

@using EShopperTheme.Models
@model RegisterViewModel
@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary("")
    <div>
        <div>
            <input data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Email" name="Email" type="text" value="" placeholder="Email" />
        </div>
    </div>
    <div>
        <div>
            <input data-val="true" data-val-length="The Password must be at least 6 characters long." data-val-length-max="100" data-val-length-min="6" data-val-required="The Password field is required." id="Password" name="Password" type="password" placeholder="Password" />
        </div>
    </div>
    <div>
        <div>
            <input data-val="true" data-val-equalto="The password and confirmation password do not match." data-val-equalto-other="*.Password" id="ConfirmPassword" name="ConfirmPassword" type="password" placeholder="Confirm Password" />
        </div>
    </div>
    <div>
        <div>
            <button type="submit" class="btn btn-default">Register</button>
        </div>
    </div>
}

当我进入登录页面时,如果我输入数据库中存在的正确数据,所以它不会给我任何错误,但是当我输入任何(Null)或只是输入一些错误的数据时,它给了我传递到字典中的模型项类型为 Models.LoginViewModel ,但此字典需要类型为 Models.RegisterViewModel Error 的模型项。知道吗?

PS:值得一提的是,我在寄存器视图模型中使用了简单的 Html 标签,因为我无法作为 Razor 来做到这一点。 :(

如何处理 传递到字典中的模型项是 LoginViewModel 类型,但此字典需要 RegisterViewModel

您需要

RegisterViewModel的新实例传递给_RegisterPartial

@Html.Partial("_RegisterPartial", new RegisterViewModel())

您的主视图假设LoginView需要LoginViewModel,但根据 MVC 规则,除非您指定新类型,否则所有分部视图的类型都与呈现它的视图相同。