简体   繁体   English

ASP.NET MVC数据验证不起作用

[英]ASP.NET MVC data validation not working

Here is the model class which has properties set as required 这是具有所需属性设置的模型类

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

namespace ArcheWeb_nuovo.Models
{
    public class Utente : InformazioniGenerali
    {

        public int ID_utente { get; set; }
        [Required]
        public string Nome { get; set; }
        [Required]
        public string Cognome { get; set; }
        [Required]
        public string Username { get; set; }
        [Required]
        public string Email { get; set; }
        [Required]
        public string CID { get; set; }
        [Required]
        public bool IsLocked { get; set; }
        [Required]
        public string Password
        {
            get
            {
                string caratteri = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                int lunghezza = 20;

                Random rnd = new Random();
                StringBuilder pw = new StringBuilder(lunghezza);
                for (int i = 0; i < lunghezza; i++)
                {
                    pw.Append(caratteri[rnd.Next(caratteri.Length)]);
                }
                string password = pw.ToString();
                return password;

            }
        }
        public string Visualizzazione
        {
            get
            {
                return Cognome.ToUpper() + " " + Nome;
            }
        }




    }
}

as you can see i marked the properties as Required and yet when i press the submit button in my view it throws an exception because, obviously, the data is empty(the data is empty because i'm testing the data validation) . 如您所见,我将属性标记为“必需”,但是当我按视图中的“提交”按钮时,它会引发异常,因为显然数据为空(数据为空,因为我正在测试数据验证)。 Instead i want it to prevent the user to proceed. 相反,我希望它阻止用户继续。 What am i doing wrong? 我究竟做错了什么? Here is the HttpPost from the controller 这是来自控制器的HttpPost

[HttpPost]
        public ActionResult Create(Utente utente)
        {


            //impostazione parametri della connessione SQL
            using (SqlConnection sqlCon = new SqlConnection(ConnessioneDB.STRINGA_CONNESSIONE))
            {

                try
                {

                    //Aperura connessione
                    sqlCon.Open();
                    //assegnazione della query d'inserimento dati in una variabile
                    string query = "INSERT INTO users(nome, cognome, username, email, CID, azienda, visualizzazione, password) VALUES(@nome, @cognome, @username, @email, @CID, @azienda, @visualizzazione, @password)";
                    //impostazione del comando sqlCmd
                    SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
                    //si utilizza una query parametrizzata per evitare attacchi di SQL Injection
                    sqlCmd.Parameters.AddWithValue("@nome", utente.Nome);
                    sqlCmd.Parameters.AddWithValue("@cognome", utente.Cognome);
                    sqlCmd.Parameters.AddWithValue("@username", utente.Email);
                    sqlCmd.Parameters.AddWithValue("@email", utente.Email);
                    sqlCmd.Parameters.AddWithValue("@CID", utente.CID);
                    sqlCmd.Parameters.AddWithValue("@azienda", utente.Azienda);
                    sqlCmd.Parameters.AddWithValue("@visualizzazione", utente.Visualizzazione);
                    sqlCmd.Parameters.AddWithValue("@password", utente.Password);
                    //si fa partire la query
                    sqlCmd.ExecuteNonQuery();
                }
                catch(Exception e)
                {
                    ViewBag.errore = e.Message;
                    return View("Errore");
                }
            }
            return RedirectToAction("Successo");

        }

Before doing anything with your model, you have to proactively check if it passed validation. 在对模型进行任何处理之前,您必须主动检查它是否通过了验证。 And like @StephenMuecke and @CalC said, you need to return it to the client if it does not. 就像@StephenMuecke和@CalC所说的,如果没有,则需要将其返回给客户端。

[HttpPost]
public ActionResult Create(Utente utente)
{
    if (!ModelState.IsValid) {
        return View(utente);
    }
    // save your model      
}

Exceptions are not how the Required attribute is supposed to work, so you most likely have another, potentially unrelated error in your program. 异常不是“必需”属性的工作方式,因此您很可能在程序中遇到另一个可能不相关的错误。 Check the error message to see which function is throwing the error. 检查错误消息以查看哪个函数引发了错误。

You may also want to add specific error messages to your Required attributes. 您可能还希望将特定的错误消息添加到“必需”属性。 You can read more about them in the answer to this question . 您可以在此问题的答案中了解有关它们的更多信息。

The password property has the [required] attribute, but it has no setter. password属性具有[required]属性,但没有设置器。 You should either add a setter or remove the required attribute. 您应该添加一个setter或删除必需的属性。

[Required()]
public string Password {get; set;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM