【问题标题】:Validate Single Model on submit In MVC5在 MVC5 中提交时验证单个模型
【发布时间】:2015-02-20 16:36:23
【问题描述】:

让我解释一下我想要实现的目标。我有一个视图,其中包含部分视图,每个部分视图都有两个不同的模型。

1- 登录视图模型 2- 注册视图模型

我想要实现的只是当 Login Post 操作发生时,如果任何字段为空,则仅将 Login Model 返回到带有所有验证消息的 Partial View。

当我在验证字段时返回相同的视图时遇到问题。

这是一段代码

账户控制人:

  //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {

                var user = User.SelectByUserNameAsync(model.UserName,model.Password);
                if (user != null)
                {
                   // var x = User.SignInAsync(model);
                    return Redirect("Home/Index");
                }
                else
                {
                    ViewBag.Model = new RegisterViewModel();
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

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

登录视图:

@{
    Layout = "~/Views/Shared/_LoginLayout.cshtml";
}
<section id="page-title">

    <div class="container clearfix">
        <h1>My Account</h1>
        <ol class="breadcrumb">
            <li><a href="index.aspx">Home</a></li>
            <li><a href="#">Sign-Up</a></li>
            <li class="active">Login</li>
        </ol>
    </div>

</section><!-- #page-title end -->
<!-- Content
============================================= -->
<section id="content">

    <div class="content-wrap">

        <div class="container clearfix">

            <!--Login PartialView-->
            @{Html.RenderPartial("_LoginBox");}

            <!--Login PartialView Ends-->

            <!--Register PartialView-->
            @{Html.RenderPartial("_Register");}

            <!--Register PartialView Ends-->


        </div>

    </div>

</section><!-- #content end -->

但是当页面返回时,如果发生任何错误,它会显示错误

 The model item passed into the dictionary is of type 'ConnexMi.Models.LoginViewModel', but this dictionary requires a model item of type 'ConnexMi.Models.RegisterViewModel'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'ConnexMi.Models.LoginViewModel', but this dictionary requires a model item of type 'ConnexMi.Models.RegisterViewModel'.

Source Error:


Line 28: 
Line 29:             <!--Register PartialView-->
Line 30:             @{Html.RenderPartial("_Register");}
Line 31: 
Line 32:             <!--Register PartialView Ends-->

你能告诉我我在这段代码中做错了什么吗?谢谢

【问题讨论】:

  • 您应该做的是拥有 2 个独立的操作方法和关联的视图。它们是 2 种不同的操作,Register 无论如何都是一次性的 - 为什么要将其呈现给已经注册的用户!)。在登录页面有一个指向注册页面的链接。使您的设计工作所必需的黑客是不值得的(而且只会降低性能)
  • 嗯,这就是我的客户想要的,我不知道为什么问他这不是一个好习惯..但是无论客户说什么我都必须马上去做....

标签: asp.net-mvc asp.net-mvc-5


【解决方案1】:

您将需要一个结合了 Login 和 Register 视图模型的视图模型。例如

查看模型

public class LoginVM
{
    [Display(Name = "Email")]
    [Required(ErrorMessage = "Please enter an email address")]
    [DataType(DataType.EmailAddress)]
    [EmailAddress]
    public string Email { get; set; }

    [Required(ErrorMessage = "Please enter a password")]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
}
public class RegisterVM
{
    // properties for email, password and confirm password
}

public class LoginRegisterVM
{
    public LoginVM Login { get; set; }
    public RegisterVM Register { get; set; }
}

控制器(假设帐户)

public ActionResult Index()
{
    LoginRegisterVM model = new LoginRegisterVM();
    return View(model);
}

[HttpPost]
public ActionResult Login([Bind(Prefix="Login")]LoginVM loginModel)
{
    if (!ModelState.IsValid)
    {
        LoginRegisterVM model = new LoginRegisterVM();
        model.Login = loginModel;
        return View("Index", model);
    }
    // Login and redirect
}
[HttpPost]
public ActionResult Register([Bind(Prefix="Register")]RegisterVM registerModel)
{
    if (!ModelState.IsValid)
    {
        LoginRegisterVM model = new LoginRegisterVM();
        model.Register = registerModel;
        return View("Index", model);
    }
    // Register and redirect
}

查看

@model LoginRegisterVM

@using(Html.BeginForm("Login", "Account", FormMethod.Post)
{
    @Html.LabelFor(m => m.Login.Email)
    @Html.TextBoxFor(m => m.Login.Email)
    @Html.ValidationMessageFor(m => m.Login.Email)
    ... // other properties of login model
    <input type="submit" value="Login" />
}

@using(Html.BeginForm("Register", "Account", FormMethod.Post)
{
    // properties of register model
    <input type="submit" value="Register" />
}

【讨论】:

    猜你喜欢
    • 2018-05-31
    • 2021-09-07
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多