显示 .NET 验证错误,不带批注

.NET Validation Errors are shown without annotations

提问人:flam3shadow 提问时间:7/5/2023 更新时间:7/5/2023 访问量:30

问:

在我的 Razor 页面上,我有一个提交表单。相应的模型有一些必需的注释,我已经删除了这些注释,但仍然显示验证按摩。我正在使用 Visual Studio Community。

注册模式:

using System.ComponentModel.DataAnnotations;
using TimesheetManager.Classes;

namespace TimesheetManager.Models
{
    public class RegistrationViewModel:BaseViewModel
    {
        public RegistrationViewModel() 
        {
            Username = string.Empty;
            Email = string.Empty;
            Password = string.Empty;
            Passwordconfirmation = string.Empty;
            Firstname = string.Empty;
            Lastname = string.Empty;
            DOB = string.Empty;
            Street = string.Empty;
            Hnr = string.Empty;
            Zipcode = string.Empty;
            City = string.Empty;
            Phone = string.Empty;
            Entry = string.Empty;
            Gender = Gender.männlich;
        }

        public RegistrationViewModel(Employee profile):base(profile)
        {
            Username = string.Empty;
            Email = string.Empty;
            Password = string.Empty;
            Passwordconfirmation = string.Empty;
            Firstname = string.Empty;
            Lastname = string.Empty;
            DOB= string.Empty;
            Street = string.Empty;
            Hnr = string.Empty;
            Zipcode = string.Empty;
            City = string.Empty;
            Phone = string.Empty;
            Entry= string.Empty;
            Gender = Gender.männlich;
        }

        public RegistrationViewModel(string username, string email, string password, string passwordconfirmation,string firstname, string lastname, string dob, string street, string hnr, string zipcode, string city, string phone, string entry, Gender gender, Employee profile) : base(profile)
        {
            Username = username;
            Email = email;
            Password = password;
            Passwordconfirmation = passwordconfirmation;
            Firstname = firstname;
            Lastname = lastname;
            DOB = dob;
            Street = street;
            Hnr = hnr;
            Zipcode = zipcode;
            City = city;
            Phone = phone;
            Entry = entry;
            Gender = Gender;
        }
        
        public string Username { get; set; }
        public string Email { get; set; }
        public string Password { get; set;}
        public string Passwordconfirmation { get; set; }
        public string Firstname { get; set;}
        public string Lastname { get; set;}
        public string DOB { get; set; }
        public string Street { get; set; }
        public string Hnr { get; set; }
        public string Zipcode { get; set; }
        public string City { get; set; }
        public string Phone { get; set; }
        public string Entry { get; set; }
        public Gender Gender { get; set; }

    }
}

The Registraion.cshtml:

@model TimesheetManager.Models.RegistrationViewModel
@using TimesheetManager.Classes

@{
    ViewData["Title"] = "Registerierung";
}
<h1>Angestellten registrieren</h1>
<div class="row">
    <div class="col-md-4">
        <form asp-action="Register">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Username" class="control-label">Benutzername</label>
                <input asp-for="Username" class="form-control" />
                <span asp-validation-for="Username" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Email" class="control-label">Emailadresse</label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password" class="control-label">Passwort</label>
                <input type="password" asp-for="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Passwordconfirmation" class="control-label">Passwort bestätigen</label>
                <input type="password" asp-for="Passwordconfirmation" class="form-control" />
                <span asp-validation-for="Passwordconfirmation" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Firstname" class="control-label">Vorname</label>
                <input asp-for="Firstname" class="form-control" />
                <span asp-validation-for="Firstname" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Lastname" class="control-label">Nachname</label>
                <input asp-for="Lastname" class="form-control" />
                <span asp-validation-for="Lastname" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Street" class="control-label">Straße</label>
                <input asp-for="Street" class="form-control" />
                <span asp-validation-for="Street" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Hnr" class="control-label">Hausnummer</label>
                <input asp-for="Hnr" class="form-control" />
                <span asp-validation-for="Hnr" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Zipcode" class="control-label">Postleitzahl</label>
                <input asp-for="Zipcode" class="form-control" />
                <span asp-validation-for="Zipcode" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="City" class="control-label">Stadt</label>
                <input asp-for="City" class="form-control" />
                <span asp-validation-for="City" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Phone" class="control-label">Telefonnummer</label>
                <input asp-for="Phone" class="form-control" />
                <span asp-validation-for="Phone" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Entry" class="control-label">Einstellungsdatum</label>
                <input type="date" asp-for="Entry" class="form-control" />
                <span asp-validation-for="Entry" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DOB" class="control-label">Geburtsdatum</label>
                <input type="date" asp-for="DOB" class="form-control" />
                <span asp-validation-for="DOB" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Gender" class="control-label">Geschlecht</label>
                <select asp-for="Gender"
                        class="form-control"
                        asp-items="Html.GetEnumSelectList<Gender>()">
                </select>
                <span asp-validation-for="Gender" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Registrieren" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

控制器:

using TimesheetManager.Helpers;
using TimesheetManager.Services;
using Microsoft.AspNetCore.Mvc;
using TimesheetManager.Classes;
using TimesheetManager.Helper;
using TimesheetManager.Models;

namespace TimesheetManager.Controllers
{
    public class LoginController : Controller
    {
        private readonly ILogger<LoginController> _logger;
        private DBConnection _connection;
        private IConfiguration _configuration;
        private ConfigHelper _configHelper;

        [HttpGet]
        public IActionResult Register()
        {
            RegistrationViewModel vm = new RegistrationViewModel(new Employee());
            return View(vm);
        }

        [HttpPost]
        public IActionResult Register(RegistrationViewModel vm) 
        {
            EmployeeService service = new EmployeeService(_connection);
            if (service.UserExists(vm.Username, vm.Email))
            {
                ViewBag.Error = "Nutzername oder Email schon vorhanden";
                vm.Username = String.Empty;
                vm.Email = String.Empty;
                return View(vm);
            }
            else
            {
                if (vm.Password != vm.Passwordconfirmation)
                {
                    ViewBag.Error = "Passwörter stimmen nicht überein";
                    vm.Password = String.Empty;
                    vm.Passwordconfirmation = String.Empty;
                    return View(vm);
                }
                else 
                { 
                    Employee? employee = new Employee();
                    employee.Username = vm.Username;
                    employee.Email = vm.Email;
                    employee.City = vm.City;
                    employee.Street = vm.Street;
                    employee.Entry = new DateOnly(int.Parse(vm.Entry.Substring(0,4)), int.Parse(vm.Entry.Substring(5, 2)), int.Parse(vm.Entry.Substring(8, 2)));
                    employee.DOB = new DateOnly(int.Parse(vm.DOB.Substring(0, 4)), int.Parse(vm.DOB.Substring(5, 2)), int.Parse(vm.DOB.Substring(8, 2)));
                    employee.Firstname = vm.Firstname;
                    employee.Lastname = vm.Lastname;
                    employee.Gender = vm.Gender;
                    employee.Phone = vm.Phone;
                    employee.Hnr = vm.Hnr;
                    employee.Password = vm.Password;
                    employee.Zipcode = vm.Zipcode;
                    service.saveEmployee(employee);
                    employee = service.getEmployeeByLogin(employee.Username, employee.Password);
                    if (employee == null)
                    {
                        ViewBag.Error = "Registrierung fehlgeschlagen! Bitte wiederholen Sie den Vorgang zu einem späteren Zeitpunkt nocheinmal";
                        return View(vm);
                    }
                    else
                    {
                        return RedirectToAction("Detail", "Employee", new { id = employee.Id });
                    }
                }
                
            }
        }

        public LoginController(ILogger<LoginController> logger, IConfiguration config)
        {
            _logger = logger;
            _configuration = config;
            _configHelper = new ConfigHelper(config);
            _connection = new DBConnection(_configHelper);
        }

        [HttpGet]
        public IActionResult Login()
        {
            LoginViewModel vm = new LoginViewModel(new Employee());
            return View(vm);
        }

        public IActionResult Login(LoginViewModel lvm)
        {
            if (string.IsNullOrEmpty(lvm.Username) && string.IsNullOrEmpty(lvm.Password))
            {
                return View();
            }
            else
            {
                Employee? Employee = SignInMethod(lvm.Username, pass: lvm.Password);
                {
                    if (Employee != null)
                    {
                        return RedirectToAction("Index", "Home", new BaseViewModel(Employee));
                    }
                    return View("Login", lvm);
                }
            }
        }

        private Employee? SignInMethod(string user, string pass)
        {
            EmployeeService service = new EmployeeService(_connection);
            Employee? Employee = service.getEmployeeByLogin(user, pass);
            if (Employee != null)
            {
                string key = "loggedInUser";
                string value = Employee.Id.ToString();
                CookieOptions cookieOptions = new CookieOptions
                {
                    Expires = DateTime.Now.AddMinutes(30),
                    SameSite = SameSiteMode.None,
                    Secure = true
                };
                Response.Cookies.Append(key, value, cookieOptions);
            }
            else
            {
                ViewBag.ErrorMessage = "Username or Password wrong";
            }
            return Employee;
        }



        public IActionResult Logout()
        {
            string key = "loggedInUser";
            string value = string.Empty;
            CookieOptions cookieOptions = new CookieOptions
            {
                Expires = DateTime.Now.AddMinutes(-1),
                SameSite = SameSiteMode.None,
                Secure = true
            };
            Response.Cookies.Append(key, value, cookieOptions);
            return RedirectToAction("Index", "Home");
        }
    }
}

结果仍然是:enter image description here

但预期的行为是没有像“字段 x 是必需的”这样的警告

我没有计划如何阻止行为

C# ASP.NET-MVC 验证 批注 Razor-Pages

评论

0赞 BernardV 7/5/2023
也许尝试 ingognito 会话或手动清除浏览器缓存只是为了仔细检查?(Ctrl + F5)
0赞 SNBS 7/5/2023
它可能是标准的浏览器验证。尝试向 添加一个属性,以便浏览器不会嗅到它。novalidate="novalidate"form

答:

2赞 Mike Brind 7/5/2023 #1

如果项目文件中有,则所有字符串都将被视为必需字符串,除非它们被声明为可为 null:<Nullable>enable</Nullable>

public string? Username { get; set; }
public string? Email { get; set; }

模型活页夹不认为空字符串有效。

或者,您可以为项目禁用:Nullable

<Nullable>disable</Nullable>

评论

0赞 flam3shadow 7/5/2023
谢谢,我必须通过添加问号来定义不需要为空的字段。它解决了这个问题。