3
To prevent validations made with Data Annotations are lost if the table structure changes, it is necessary to create another class with fields for validation and a class partial
, path that this last class refers to the class generated by Entity Framework. And these classes should stay 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);
}
But even empty the field Nome
, ModelState.isValid
always is true
.
Why does this happen? ModelState.isValid
should return false
.
Ever tried to make
if (status!= null && ModelState.IsValid) {...}
?– stderr
I tried, but it still wasn’t. The
status
is not coming null.– Luídne
How you are calling is ACTION in the controller?
– PauloHDSousa