To prevent validations made with Data Annotations are lost if the table structure changes, it is necessary to create another class with the fields for validation and a class partial
, path that this last class references the class generated by the Entity Framework . And these classes should look like these:
Metadata.cs
namespace BancoDeHoras.Models
{
public class StatusMetadata
{
[Required(ErrorMessage="Nome deve ser preenchido.")]
public string Nome {set;get;}
}
}
PartialClasses.cs
namespace BancoDeHoras.Models
{
[MetadataType(typeof(StatusMetadata))]
public partial class Status{}
}
Status.cs (generated class)
namespace BancoDeHoras.Data
{
//usings omitidos
public partial class Status
{
public int Id { get; set; }
public string Nome { get; set; }
public string Descricao { get; set; }
}
}
Controller
[HttpPost]
public ActionResult Cadastrar(Status status)
{
if (ModelState.IsValid)
{
try
{
using (BancoDeHorasEntities banco = new BancoDeHorasEntities())
{
banco.Entry(status).State = System.Data.Entity.EntityState.Added;
banco.SaveChanges();
TempData["s"] = "Cadastro realizado com sucesso!";
ModelState.Clear();
return View();
}
}
catch (Exception)
{
TempData["e"] = "Não foi possível cadastrar!";
}
}
return View(status);
}
However, even empty the Nome
field, ModelState.isValid
is always true
.
Why does it happen? ModelState.isValid
should return false
.