Way to save only two information

Asked

Viewed 54 times

0

I have in my project a new business rule.

I need that in a view details, I have a small form to save only two information: Delays and No Uniform.

I already got the chart done. But I needed that form to save only those two information, and not the whole object, because it is already loaded into the detail page.

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

What I got 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 don’t know if it’s right... so I haven’t even done the form.

Could someone help me ?

  • The object to be saved already exists or you are creating it by form?

  • There is already Gypsy. Also because I seek information on view details to show the information to the user. I just wanted to add this information to the object.

1 answer

1


Since it is an update, it is wrong to add the object in context. You need to retrieve 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.