ModelState.IsValid无法正常工作

时间:2015-11-18 13:11:00

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

有2个型号
的usermodel

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace TaskManager.Models
{
    public class UserModel
    {
        private const int NAME_LENGTH = 200;
        private const int EMAIL_LENGTH = 100;

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [StringLength(NAME_LENGTH)]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        [StringLength(EMAIL_LENGTH)]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(200)]
        public string Password { get; set; }

        public string PasswordSalt { get; set; }

        [Required]
        [DefaultValue(UserType.User)]
        public UserType Type { get; set; }

        public ICollection<Task> Tasks { get; set; }
    }

    public enum UserType
    {
        Admin = 0,
        User = 1
    }
}

RegisterUserModel

public class RegisterUserModel
{
    private const int NAME_LENGTH = 200;
    private const int EMAIL_LENGTH = 100;
    private const int PASSWORD_MIN_LENGTH = 5;
    private const int PASSWORD_MAX_LENGTH = 20;

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(NAME_LENGTH)]
    public string Name { get; set; }

    [Required]
    [EmailAddress]
    [StringLength(EMAIL_LENGTH)]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [StringLength(PASSWORD_MAX_LENGTH, MinimumLength = PASSWORD_MIN_LENGTH)]
    public string Password { get; set; }

    public string PasswordSalt { get; set; }

    [Required]
    [DefaultValue(UserType.User)]
    public UserType Type { get; set; }

    public ICollection<Task> Tasks { get; set; }
}

我使用RegisterUserModel作为用户注册的视图模型

@model TaskManager.Models.RegisterUserModel

@{
    ViewBag.Title = "Registration";
}

<div class="col-md-6">
    <h2>Registration</h2>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(u => u.Name)
            @Html.TextBoxFor(u => u.Name, new { @class = "form-control" })
            @Html.ValidationMessageFor(u => u.Name, null, new { @class = "error" })
        </div>

        <div class="form-group">
            @Html.LabelFor(u => u.Email)
            @Html.TextBoxFor(u => u.Email, new { @class = "form-control" })
            @Html.ValidationMessageFor(u => u.Email, null, new { @class = "error" })
        </div>

        <div class="form-group">
            @Html.LabelFor(u => u.Password)
            @Html.PasswordFor(u => u.Password, new { @class = "form-control" })
            @Html.ValidationMessageFor(u => u.Password, null, new { @class = "error" })
        </div>

        <div>
            <input type="submit" class="btn btn-default" value="Registration" />
        </div>
    }
</div>

UserController

[HttpGet]
public ActionResult Registration()
    {
        var registerUser = new RegisterUserModel();
        return View(registerUser);
    }

[HttpPost]
public ActionResult Registration(RegisterUserModel registerUser)
{
    var user = new UserModel
    {
        Name = registerUser.Name,
        Email = registerUser.Email,
        Password = registerUser.Password
    };

    if (ModelState.IsValid)
    {
        if (!IsUserExist(registerUser.Email))
        {    

            var crypto = new SimpleCrypto.PBKDF2();

            var encrpPass = crypto.Compute(user.Password);

            var newUser = _db.Users.Create();

            newUser.Name = user.Name;
            newUser.Email = user.Email;
            newUser.Type = UserType.User.ToString();

            newUser.Password = encrpPass;
            newUser.PasswordSalt = crypto.Salt;

            _db.Users.Add(newUser);
            _db.SaveChanges();

            return RedirectToAction("Index", "Task");

        }
        else
        {
            ModelState.AddModelError("", User already exists");
        }
    }
    else
    {
        ModelState.AddModelError("", "Incorrect data");
    }

    return View(user);
}

但是当我尝试使用DB中已存在的电子邮件注册用户时,我得到了Exception

  

传入字典的模型项类型为&#39; TaskManager.Models.UserModel&#39;,但此字典需要一个模型   类型&#39; TaskManager.Models.RegisterUserModel&#39;。

     

System.InvalidOperationException:传入字典的模型项类型为&#39; TaskManager.Models.UserModel&#39;,但是这个   字典需要类型的模型项   &#39; TaskManager.Models.RegisterUserModel&#39;

我做错了什么?如何解决?

1 个答案:

答案 0 :(得分:2)

您的问题就在底部,您正在将用户传递给View函数而不是registerUser。