How to save only two information

0

I have a new business rule in my project.

I need a details view, so I have a small form to save only two information: Delay and No Uniform.

I already have the table made. But I needed this form to save only those two information, not the entire object, because it is already loaded on the detail page.

How can I make a action that only save this information?

What I already have is this:

 public ActionResult Controle([Bind(Include = "AlunoID,Atrasos,SemUniforme")] Aluno aluno)
    {
        if (ModelState.IsValid)
        {
            db.Alunos.Add(aluno);
            db.SaveChanges();
        }
        return View(aluno);
    }

But I do not know if it's right ... That's why I have not even done form .

Could anyone help me?

    
asked by anonymous 31.12.2014 / 00:39

1 answer

1

Because it is an update, it is wrong to add the object in context. You must recover the old object and update field by field:

public ActionResult Controle([Bind(Include = "AlunoID,Atrasos,SemUniforme")] Aluno aluno)
{
    var alunoOriginal = db.Alunos.SingleOrDefault(x => x.AlunoID == aluno.AlunoId);

    if (ModelState.IsValid)
    {
        alunoOriginal.Atrasos = aluno.Atrasos;
        alunoOriginal.SemUniforme = aluno.SemUniforme;
        db.Entry(alunoOriginal).State = EntityState.Modified;
        db.SaveChanges();
    }

    return View(alunoOriginal);
}
    
31.12.2014 / 03:02