在MVC5中提交时验证单个模型

时间:2015-02-20 16:36:24

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

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

1- LoginViewModel 2- RegisterViewModel

我想要实现的只是当Login Post操作发生时,如果任何字段为空,则只返回带有所有验证消息的部分视图的登录模型。

当验证字段时出现任何错误时,我返回相同的视图时遇到问题。

这是一段代码

帐户管理员:

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

LoginView:

@{
    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-->

请告诉我这段代码中我做错了什么?感谢

1 个答案:

答案 0 :(得分: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" />
}