0

Well I'm trying to do a many to many relationship with my Desafio(challenge) and my Tag model, a challenge can have many tags and a tag can be related to many challenges, I already placed the tags on the view, the problem is when I submit the form, it says that the value is null on this line:

var DesafioTag = new HashSet<int>(
         desafio.Tags.Select(a => a.Id));

I will show how I did:

my models

Tag~

 public class Tag
{
    public int Id { get; set; }
    public string NomeTag { get; set; }
    public string cor { get; set; }
    public virtual ICollection<ApplicationUser> Users { get; set; }
    public virtual ICollection<Desafio> Desafios { get; set; }
}

Desafio(challenge)

 public class Desafio
{
    public int DesafioId { get; set; }

    public string TipoTrabalho { get; set; }

    public virtual ApplicationUser User { get; set; }

    public string ApplicationUserId { get; set; }

    public string Descricao { get; set; }
    public int TipoAvaliacaoId { get; set; }
    public virtual TipoAvaliacao TipoAvaliacao { get; set; }       
    public decimal valor { get; set; }
    public int Visualizacoes { get; set; }
    public DateTime DataCriacao { get; set; }
    public decimal lat { get; set; }
    public decimal lon { get; set; }
    public int IdSolucaoVencedora { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }

}

then i have 2 viewmodels to display the data in the view

DesafioCreate

public class DesafioCreate
{
    public string Desafio { get; set; }
    public string Descricao { get; set; }
    public decimal ValorMonetario { get; set; }
    public decimal lat { get; set; }
    public decimal lon { get; set; }
    public ICollection<TagDesafio> TagDesafio { get; set; }
}

 public class TagDesafio
{
    public int TagId { get; set; }
    public string Nome { get; set; }
    public bool Seleccionado { get; set; }
}

I already did something with many to many relationships to edit, and I did it, but in a create method it doesn't work, I feel that has something to do with my challenge, cause I'm trying to associate tags with a challenge that doesn't exist, but I don't know if the cause is that, here is the post code that I think is the main problem here

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(DesafioCreate model, string[] selectedTag,HttpPostedFileBase file)
    {
        TipoAvaliacao TipoAvaliacao = db.TiposAvaliacao.Where(i => i.TipoAvaliacaoId == 1).FirstOrDefault();

        if (ModelState.IsValid)
        {
            Desafio desafio = new Desafio();
            desafio.lat = model.lat;
            desafio.lon = model.lon;
            desafio.TipoTrabalho = model.Desafio;
            desafio.Descricao = model.Descricao;
            desafio.DataCriacao = DateTime.Now;
            desafio.TipoAvaliacao = TipoAvaliacao;
            desafio.valor = 22;
            desafio.Visualizacoes = 34;
            desafio.ApplicationUserId = User.Identity.GetUserId();


            var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Anexos"), fileName);
                    var anexo = new Anexo();
                    anexo.Caminho = path;
                    anexo.NomeFicheiro = fileName;
                    anexo.DesafioId = desafio.DesafioId;

                db.Desafios.Add(desafio);

            atualizarTagsDesafio(desafio, selectedTag);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        preencherTagDesafio();
        return View(model);
    }

    private void atualizarTagsDesafio(Desafio desafio,


string[] selectedTag)
        {
            if (selectedTag == null)
            {
                desafio.Tags = new List<Tag>();
                return;
            }
            var selectedAutoresHS = new HashSet<string>(selectedTag);
            var DesafioTag = new HashSet<int>( // line that cause the error
             desafio.Tags.Select(a => a.Id));  // line that cause the error
            var Tags = db.Tags;
            foreach (var tag in Tags)
            {
                if (selectedAutoresHS.Contains(tag.Id.ToString()))
                {
                    if (!DesafioTag.Contains(tag.Id))
                    {
                        desafio.Tags.Add(tag);
                    }
                }
                else {

                    if (DesafioTag.Contains(tag.Id))
                    {
                        desafio.Tags.Remove(tag);
                    }
                }
            }
        }

If someone can give me a hand, I'm a beginner doing this relationships, and I cant find the problem.

Ps: Sorry for my bad English

Malik Khalil
  • 5,196
  • 1
  • 31
  • 30

1 Answers1

0

What does your view look like. In order to submit a list/collection of things the modelbinder want html elements with id's like "TagDesafio[0].TagId, TagDesafio1.TagId" etc

Check this post for more: [MVC Form not able to post List of objects

[2]: MVC Form not able to post List of objects

Updated answer after examining your code more closely.

I see now that you are creating a new Desafio and adding it to the db-context. You then try to access the Tags associated with it. Please chech that you either have lazy loading enabled or load the Tags collection explicitly.

Check out the documentation for loading related entities: https://msdn.microsoft.com/en-us/data/jj574232.aspx

Alternatively, in this case, you could instantiate the Desafio object with an emtpty tag collection:

Desafio desafio = new Desafio();
desafio.Tags = new Collection<Tags>();
Community
  • 1
  • 1
Indregaard
  • 1,155
  • 1
  • 17
  • 24