0

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

        }
  • Please share the code for your controller (or at least the `HttpPost` action). Also, what exception is being thrown? – SpruceMoose Jan 25 '18 at 21:29
  • edited the original post! – Edi Lipovac Jan 25 '18 at 21:38
  • Have you even implemented client side validation? And you always include `if (!ModelState.IsValid) { return View(utente) }` in the controller method to check if the model is invalid, and return it so that the user can correct errors. –  Jan 25 '18 at 21:41
  • 2
    You should read [Can we stop using AddWithValue Already?](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) – mason Jan 25 '18 at 21:43

3 Answers3

1

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.

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

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 exceptions are thrown becuase i'm purposefully leaving the the data empty in order to test the data validation! There is no error in my code – Edi Lipovac Jan 25 '18 at 21:41
0

The password property has the [required] attribute, but it has no setter. You should either add a setter or remove the required attribute.

[Required()]
public string Password {get; set;}
  • What is the property is readonly or has no setters. Any way to get the required property to work? – Enrico Mar 31 '22 at 11:48