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

        }
4
  • Please share the code for your controller (or at least the HttpPost action). Also, what exception is being thrown? Commented Jan 25, 2018 at 21:29
  • edited the original post! Commented Jan 25, 2018 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. Commented Jan 25, 2018 at 21:41
  • 2
    You should read Can we stop using AddWithValue Already? Commented Jan 25, 2018 at 21:43

3 Answers 3

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      
}
Sign up to request clarification or add additional context in comments.

2 Comments

Also note that if the ModelState is not valid, you need to return View(model) to display the validation errors
that did the trick, thanks! also thanks to @mason for the article :)
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.

1 Comment

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
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;}

1 Comment

What is the property is readonly or has no setters. Any way to get the required property to work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.