0

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

我应用注释的模型

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

2 回答 2

1

您应该没有所需属性 Employee.FirstName、Employee.LastName、Employee.Gender、Employee.DateOfBirth 的编辑器或隐藏字段。所以这个属性的验证失败。

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

于 2013-02-01T12:16:06.500 回答
1

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

例如:从 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,您应该花一些时间来更深入地研究服务器端与客户端验证。

于 2013-02-01T13:21:08.253 回答