添加注释后,ModelState.IsValid变为false

时间:2013-02-01 11:45:28

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

在我的应用程序中如果我向模型属性添加注释,则ModelState.IsValid将变为false。 如果我删除所有注释,那么它就成了现实。 当我添加注释时,它注释确实有效,但即使字段为空也不会发生代码。 我正在使用mvc4 razor。

我已应用注释的模型

using System.ComponentModel.DataAnnotations;

namespace HRMDatabaseLayer.Entities
{
using System;
using System.Collections.Generic;

public partial class EmployeeDetail
{
    public EmployeeDetail()
    {
        this.EmployeeContactDetails = new HashSet<EmployeeContactDetail>();
        this.EmployeeDepartments = new HashSet<EmployeeDepartment>();
        this.EmployeeEducations = new HashSet<EmployeeEducation>();
        this.EmployeeExperiances = new HashSet<EmployeeExperiance>();
        this.EmployeeFamilies = new HashSet<EmployeeFamily>();
        this.EmployeeLanguages = new HashSet<EmployeeLanguage>();
        this.EmployeeSkills = new HashSet<EmployeeSkill>();
    }

    public int Id { get; set; }

    [Required(ErrorMessage = "First Name is Required")]
    public string FirstName { get; set; }
    public string MiddleName { get; set; }

    [Required(ErrorMessage = "Last Name is Required")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Employee Id is Required")]
    public string EmployeeId { get; set; }

    [Required(ErrorMessage = "Gender is Required")]
    public string Gender { get; set; }

    public string MaritalStatus { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Required(ErrorMessage = "Birth Date is Required")]
    public System.DateTime DateOfBirth { get; set; }

    public string IsAdmin { get; set; }
    public byte[] Picture { get; set; }

    [Required(ErrorMessage = "Password is Required")]
    public string Password { get; set; }

    public virtual ICollection<EmployeeContactDetail> EmployeeContactDetails { get; set; }
    public virtual ICollection<EmployeeDepartment> EmployeeDepartments { get; set; }
    public virtual ICollection<EmployeeEducation> EmployeeEducations { get; set; }
    public virtual ICollection<EmployeeExperiance> EmployeeExperiances { get; set; }
    public virtual ICollection<EmployeeFamily> EmployeeFamilies { get; set; }
    public virtual ICollection<EmployeeLanguage> EmployeeLanguages { get; set; }
    public virtual ICollection<EmployeeSkill> EmployeeSkills { get; set; }
}
}

这是我的观点

<div>
@using (Html.BeginForm("Login", "Login"))
{
    <table>
        <tr>
            <td>
                <h3>Login</h3>
            </td>
        </tr>
        <tr>
            <td>Employee Id :
            </td>
            <td>
                @Html.EditorFor(model => @model.Employee.EmployeeId)
            </td>
            <td>
                @Html.ValidationMessageFor(model => @Model.Employee.EmployeeId)
            </td>
        </tr>
        <tr>
            <td>
                Password : 
            </td>
            <td>
                @Html.EditorFor(model => @Model.Employee.Password)
            </td>
            <td>
                @Html.ValidationMessageFor(model => @Model.Employee.Password)
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input type="submit" value ="Login" />
            </td>
        </tr>
    </table>
    @Html.ValidationSummary(true)
}
<br />
</div>

这是我使用ModelState.IsValid

的控制器代码
public ActionResult Login(LoginViewModel empDetails)
    {
        if (ModelState.IsValid)
        {
            if (ValidateUser(empDetails.Employee.EmployeeId, empDetails.Employee.Password))
            {
                Session["id"] = empRepository.GetEmpId(empDetails.Employee.EmployeeId);
                FormsAuthentication.SetAuthCookie(empDetails.Employee.EmployeeId, false);
                return RedirectToAction("Index", "User", new { area = "EmployeeDetails" });
            }
            else
            {
                ViewBag.LoginError = "The user name or password provided is incorrect.";
            }
        }
        empDetails.Employee.Password = string.Empty;
        return View("Index", empDetails);
    }

2 个答案:

答案 0 :(得分:1)

您应该没有所需属性的编辑器或隐藏字段Employee.FirstName,Employee.LastName,Employee.Gender,Employee.DateOfBirth。因此,对此属性的验证失败。

如果您只想从客户端获取EmployeeId和Password,则应使用仅包含这两个属性的另一个模型。

答案 1 :(得分:1)

如果您不需要firstName,lastName等字段,那么它们不应该是发送到视图的模型的一部分。您应该创建一个仅包含该视图所需属性的View Model,并将数据注释放在那里,而不是注释并将您的域模型发送到视图。

例如: 从EmployeeDetail类中删除所有数据注释,然后

public class LoginViewModel
{
    [Required(ErrorMessage = "Employee Id is Required")]
    public string EmployeeId { get; set; }
    [Required(ErrorMessage = "Password is Required")]
    public string Password { get; set; }
    //others you need for this view
}

现在强烈输入您对此模型的视图。 ModelState现在只关心视图模型中所需的属性,而不关心视图中不需要的任何属性。

至于你对“仍然命中代码”的评论,你可能只需要添加

<configuration>
    <appSettings>
        <add key="ClientValidationEnabled" value="true"/>
        <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    </appSettings>
</configuration>

到您的Web.Config,您应该花一些时间深入研究服务器端与客户端验证。

相关问题