比较使用.net在验证表单中字符串是否有效

问题描述

我有一个带有该div的创建表单

<div>
    <label asp-for="Department">Department</label>
    <select asp-for="Department" asp-items="Html.GetEnumSelectList<OptionListDepartments>()"></select>
    <span asp-validation-for="Department" class="text-danger"></span>
</div>

所以在这个div中,我将显示以下内容

enter image description here

我以此方式在控制器中创建了create方法

[HttpPost("home/create")]
    public IActionResult create(Employee e)
    {
        if(ModelState.IsValid)
        {
            _employeeRepository.addEmployee(e);

            return RedirectToAction("/");
        }
        else
        {
            return View("/Views/Home/Create.cshtml");
        }
        
    }

所以,我只检查员工是否有效,如果是,我将添加。如果无效,我将在视图中显示一些建议和危险消息。 因此,我将检查用户是否选择部门。换句话说,我将检查员工中是否有字符串“ None”,这意味着用户不要选择,而select中的选项。因此,在这种情况下,我将设置“选择部门”。我会有这样的东西:

enter image description here

为实现此目标,因此我将对类使用一些验证,例如使用System.ComponentModel.DataAnnotations compareAttribute。所以我想写这样的东西:

public class Employee
{
    public int id { get; set; }

    [required]
    public string Matricola { get; set; }

    [required]
    public string Name { get; set; }

    [required]
    public string Email { get; set; }

    //Todo understand how I can compare this field with a string
    //if I receive string "None",employee is invalid and I have to notificate to user in view
    [Compare("None",ErrorMessage ="choose a department from list")]
    public OptionListDepartments Department { get; set; }

OptionListDepartments只是一个像这样的枚举:

public enum OptionListDepartments
{
    None,IT,HR,Payroll
}

我如何实现我的目标? 感谢您的建议。

解决方法

我找到了解决问题的解决方案! 我刚刚在模型中创建了一个变量,并在构造函数中分配了一个静态值。因此,该类如下所示:

public class Employee
{
    public int id { get; set; }

    //none variable for compare,only get,you cannot set it
    public string noneDepartment {get;}

    [Required]
    [MaxLength(6,ErrorMessage ="matricola cannot exceed 6 chars")]
    public string Matricola { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    //[RegularExpression("some",ErrorMessage ="email non valida")]
    public string Email { get; set; }

    //if string from form is equal noneDepartment(setted in costructor with "NONE")
    //so we'll show an error message
    [Compare("noneDepartment",ErrorMessage ="Choose a department from list")]
    public OptionListDepartments Department { get; set; }

    public string Image { get; set; }

    public Employee()
    {
        noneDepartment = "None";
    }

它正常工作,就像您使用javascript看到选项中的无效值(例如-1)一样。