Edit two tables simultaneously in an "Edit" view

Asked

Viewed 122 times

2

I have two tables: Pessoa and Catequizando, with a 1:1 ratio and want to make a "Get" to the data of the two tables, both "id s" are equal, so I did the

Catequizando catequizando = db.Catequizando.Find(id);
Pessoa pessoa = db.Pessoa.Find(id);

I don’t know how to do the return view of the 2 tables.

Controller:

  public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Catequizando catequizando = db.Catequizando.Find(id);
            Pessoa pessoa = db.Pessoa.Find(id);
            if (catequizando == null)
            {
                return HttpNotFound();
            }

            ViewBag.CatequizandoID = new SelectList(db.Pessoa, "PessoaID", "Nome", catequizando.CatequizandoID);
            return View(catequizando);
        }
  • Unfortunately you didn’t answer my question, I can do @create between 2 models in the view, using a viewmodel, but I can’t "get" the data from 2 tables in Edit.

  • I think I got it, your problem is in . Find(id) ? because in the question you put "I don’t know how to do the 2 tables' view." ?

  • @Brunno Why did you erase your answer?

  • @I think I ran away from what he was asking

  • @Brunno did not run away no. This is the right way. Only a few things are missing.

1 answer

2


You can create an intermediate class (view model), where you will have two attributes, one of the type Catechizing and Person example:

public class CadastroViewModel
{
    public Catequizando catequizando { get; set; }        
    public Pessoa pessoa { get; set; }
}

Now pass this class in your view model, and then get it in your controller. To access the attributes in the view just do the normal process:

@model caminho.CadastroViewModel

@Html.EditorFor(model => model.catequizando.SEUATRIBUTO)
@Html.EditorFor(model => model.pessoa.SEUATRIBUTO)

In your case it would look like this:

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    Catequizando catequizando = db.Catequizando.Find(id);
    Pessoa pessoa = db.Pessoa.Find(id);

    CadastroViewModel cadastro = new CadastroViewModel();
    cadastro.catequizando = catequizando;
    cadastro.pessoa = pessoa;

    if (catequizando == null)
    {
        return HttpNotFound();
    }

    ViewBag.CatequizandoID = new SelectList(db.Pessoa, "PessoaID", "Nome", catequizando.CatequizandoID);
    return View(cadastro);
}
  • My problem is not in the view, but in the controller, to re-turn the data I will edit from 2 tables.

  • updated the code above a look!

  • Yes that’s my answer, but I can’t get to the table fields.

  • Problem solved. You have the right answer.

Browser other questions tagged

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