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]
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");
}