Validation model always fails

1

I have the following templates:

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 it to the database I report 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 LocalId is required, and it is, but I'm putting the value in the breakpoint if I look at the locals of the model is there value and yet fails.

The only way I was able to do this is by typing a field named LocalId and bringing the value of the form so it still recognizes and validation does not fail.

What can it be?

    
asked by anonymous 11.09.2014 / 20:23

2 answers

1

This is because the Model is only validated before the Controller is executed, changing the value of the model will not change the value of ModelState.IsValid

In your case you could remove [Required] from LocalId since it is not required to fill this field with the user, it will be filled by your program.

    
11.09.2014 / 20:41
2

You can use the following method: ModelState.Clear (); to clear the model state and re-run the ModelState.IsValid.

ModelState.Clear () makes a revalidation based on the currently populated model, already with its changes after sending the form, already in Action. Your method would look like this:

[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult _Create(Grupo model)
{
    model.LocalId = SessionContext.LocalSelecionado;

    ModelState.Clear();

    if (ModelState.IsValid)
    {
        _service.Add(model);
        return RedirectToAction("_List");
    }

    return PartialView(model);
}
    
11.09.2014 / 21:32