1
I have the following models:
public class Local {
[Key]
public int Id { get; set; }
public virtual Grupo Grupo { get; set; }
}
public class Grupo
{
[Key]
public int Id { get; set; }
[Required]
public int? LocalId { get; set; }
[Required]
[StringLength(60)]
public string Nome { get; set; }
[ForeignKey("LocalId")]
public virtual Local Local { get; set; }
}
In my controller before validating the model and adding to the database I inform the id
of Local
through a Session.
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult _Create(Grupo model)
{
model.LocalId = SessionContext.LocalSelecionado;
if (ModelState.IsValid)
{
_service.Add(model);
return RedirectToAction("_List");
}
return PartialView(model);
}
Every time the validation fails saying that the LocalId
is mandatory, and is, but I’m putting the value, at the breakpoint if I look at the locals of model is there the value and yet fails.
The only way I could do it is in the form by putting a field with name LocalId
and bringing the value of the form so it also continues to recognize and the validation does not fail.
What can it be?
Yeah, thanks for the tip!
– Trxplz0
I’m not sure about this, but if I’m not mistaken Clear will remove all errors found at validation time and so Isvalid will return true, however it will not revalidate the model
– Leandro Godoy Rosa
@Leandrogodoyrosa understand your concern, but in the tests I did, he revalidated, if there is still data that should be validated the errors are still returned.
– e.leal.br