[英]ASP.NET MVC data validation not working
这是具有所需属性设置的模型类
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;
}
}
}
}
如您所见,我将属性标记为“必需”,但是当我按视图中的“提交”按钮时,它会引发异常,因为显然数据为空(数据为空,因为我正在测试数据验证)。 相反,我希望它阻止用户继续。 我究竟做错了什么? 这是来自控制器的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");
}
在对模型进行任何处理之前,您必须主动检查它是否通过了验证。 就像@StephenMuecke和@CalC所说的,如果没有,则需要将其返回给客户端。
[HttpPost]
public ActionResult Create(Utente utente)
{
if (!ModelState.IsValid) {
return View(utente);
}
// save your model
}
异常不是“必需”属性的工作方式,因此您很可能在程序中遇到另一个可能不相关的错误。 检查错误消息以查看哪个函数引发了错误。
您可能还希望将特定的错误消息添加到“必需”属性。 您可以在此问题的答案中了解有关它们的更多信息。
password属性具有[required]属性,但没有设置器。 您应该添加一个setter或删除必需的属性。
[Required()]
public string Password {get; set;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.