How to add data using Begincollection and Partialviews

Asked

Viewed 68 times

1

I was able to do the system with data insertion with Begincollection and Partialviews as per seen in this question. Continuing the same, as would the editing part of the data registered in the database?

Example: I registered a collection point with two types of garbage (plastic and paper). Later, I want to include another type of garbage (aluminum). How to make the lines already filled with the previously chosen data?

EDIT1: Follow the print with two errors. It cannot find the definition of Typodetrash and Pontodecoletaid. But they exist in the Collection.

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

The rest of the code I adapted some things and it’s OK.


EDIT1: Follow the print with two errors. It cannot find the definition of Typodetrash and Pontodecoletaid. But they exist in the Collection.

Erro no TipoDeLixoErro no PontoDeColetaId

The rest of the code I adapted some things and it’s OK.

1 answer

2


Starting with your edition:

// GET: PontosDeColeta/Edit/5
public ActionResult Edit(Guid? id)
{

    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    // Estou modificando esta linha
    var pontoDeColeta = db.PontoDeColeta
                          .Include(pc => pc.PontosDeColetaTiposDeLixo.Select(pctl => pctl.TipoDeLixo))
                          .FirstOrDefault(pc => pc.Id == id);

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

    pontoDeColeta.UsuarioResponsavel = User.Identity.GetUserId();

    // Aqui também.
    ViewBag.Lixo = db.TiposDeLixo.ToList();
    return View(pontoDeColeta);
}

In the POST:

[HttpPost]
[ValidateAntiForgeryToken]
// Atenção ao Bind!
public ActionResult Edit([Bind(Include = "Id,NomePopular,Endereco,Cidade,Estado,Latitude,Longitude,InfoAdicional,Ativo,Apelido,UsuarioResponsavel,PontosDeColetaTiposDeLixo")] PontoDeColeta pontoDeColeta)
{
    if (ModelState.IsValid)
    {
        db.Entry(pontoDeColeta).State = EntityState.Modified;
        db.SaveChanges();

        // Tipos de Lixo Originais
        var tiposDeLixoOriginais = db.PontosDeColetaTiposDeLixo.AsNoTracking().Where(pctl => pctl.Id == pontoDeColeta.Id).ToList();

        // Tipos de Lixo Excluídos
        foreach (var tipoDeLixoOriginal in tiposDeLixoOriginais)
        {
            if (!pontoDeColeta.PontosDeColetaTiposDeLixo.Any(pctl => pctl.PontoDeColetaTipoDeLixoId == tipoDeLixoOriginal.PontoDeColetaTipoDeLixoId))
        {
            var tipoDeLixoExcluido = db.PontosDeColetaTiposDeLixo.Single(pctl => pctl.Id == tipoDeLixoOriginal.Id);
            db.PontosDeColetaTiposDeLixo.Remove(tipoDeLixoExcluido);
            db.SaveChanges();
        }
    }

    // Tipos de Lixo Inseridos
    foreach (var tipoDeLixo in pontoDeColeta.PontosDeColetaTiposDeLixo)
    {
        if (!tiposDeLixoOriginais.Any(pctl => pctl.Id == tipoDeLixo.Id))
        {
            // Tipo de Lixo associado não existe ainda. Inserir.
            tipoDeLixo.PontoDeColetaId = pontoDeColeta.Id;
            db.PontosDeColetaTiposDeLixo.Add(tipoDeLixo);
        }

        db.SaveChanges();
        return RedirectToAction("Index");
    }

    // Se a atualização falhar, você precisa carregar de novo os tipos de lixo.
    ViewBag.Lixo = db.TiposDeLixo.ToList();
    return View(pontoDeColeta);
}
  • In this passage: // Estou modificando esta linha
 var pontoDeColeta = db.PontoDeColeta
 .Include(pc => pc.PontosDeColetaTiposDeLixo.TipoDeLixo)
 .FirstOrDefault(pc => pc.PontoDeColetaId == id); In the pc.PontosDeColetaTiposDeLixo.TipoDeLixo it shows error saying it does not find the definition of Typodetrash. I will edit the question with the prints.

  • The example I put up is not just copy and paste. You have to use the keys according to your Models. I edited it based on your first question.

  • 1
  • Correct. I adapted the code. I just didn’t notice the PontoDeColetaId. The rest I had already changed before. Only Error in TipoDeLixo continues. I understood the logic of the code but I was in doubt really in this part where is the error. With this code pc => pc.PontosDeColetaTiposDeLixo.TipoDeLixowould it be to fill Collection with the waste that has already been selected by the user? Why does it seem that he doesn’t find the types of garbage inside the Collection.

  • Ah, yes. Is that the cardinality of PontosDeColetaTiposDeLixo is N, so you actually have to use .Include(pc => pc.PontosDeColetaTiposDeLixo.Select(pctl => pctl.TipoDeLixo)). I’ve adjusted the answer.

  • It was missing to close a key in: return RedirectToAction("Index");
 }
}//Ficou faltando essa chave
 // Se a atualização falhar, você precisa carregar de novo os tipos de lixo.
 ViewBag.Lixo = db.TiposDeLixo.ToList();

  • But by correcting the lock of the key, at the time of saving the edit, an error message is displayed: An Exception of type 'System.Invalidoperationexception' occurred in Entityframework.dll but was not handled in user code Additional information: A referential Integrity Constraint Violation occurred: The Property.

  • I think I’ve identified the problem. It seems that when you add new types of trash in the edit, Pontodecoletaid is getting null in the added line.

  • You can fix this part in Controller, if you prefer.

Show 4 more comments

Browser other questions tagged

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