Quindi ho una vista denominata indice che espone tutti i thread nel mio database. Quindi all'interno di quella vista sto caricando tutti i commenti sui thread. Quando invoco il mio modulo che dovrebbe creare un nuovo commento, continua a dirmi che lo stato del mio modello non è valido. Mi dice che non può convertire da tipo stringa a tipo profilo o commento o tag. Inizialmente ho avuto questo come il mio codice:Stato modello non valido
public ActionResult AddComment(Thread thread, string commentBody)
{
if (ModelState.IsValid)
{
_repository.AddComment(thread, comment);
TempData["Message"] = "Your comment was added.";
return RedirectToAction("Index");
}
Poi ho cambiato in questo:
public ActionResult AddComment(Thread thread, string commentBody)
{
Profile profile = _profileRepository.Profiles.FirstOrDefault(x => x.Id == thread.ProfileId);
Tag tag = _tagRepository.Tags.FirstOrDefault(t => t.Id == thread.TagId);
thread.ThreadTag = tag;
thread.Profile = profile;
Comment comment = new Comment()
{
CommentBody = commentBody,
ParentThread = thread
};
if (ModelState.IsValid)
{
_repository.AddComment(thread, comment);
TempData["Message"] = "Your comment was added.";
return RedirectToAction("Index");
}
Questo mi dice ancora che il mio modello di stato non è valido. Come ottengo in modo che non provi a cambiare lo stato?
Anche qui è la forma che viene utilizzata per chiamare questa azione:
@using(Html.BeginForm("AddComment", "Thread", mod))
{
<input type="text" name="AddComment" id="text" />
<input type="submit" value="Save"/>
}
Nel caso di codice sopra mod è il modello che è un filo. e come richiesto qui è tutto all'interno della discussione:
public Thread()
{
this.ChildComments = new HashSet<Comment>();
}
public int Id { get; set; }
public string TopicHeader { get; set; }
public string TopicBody { get; set; }
public Nullable<int> UpVotes { get; set; }
public Nullable<int> DownVotes { get; set; }
public int ProfileId { get; set; }
public int TagId { get; set; }
public virtual Profile Profile { get; set; }
public virtual ICollection<Comment> ChildComments { get; set; }
public virtual Tag ThreadTag { get; set; }
E infine la classe di commento:
public partial class Comment
{
public int Id { get; set; }
public string CommentBody { get; set; }
public int UpVotes { get; set; }
public int DownVotes { get; set; }
public virtual Thread ParentThread { get; set; }
}
è necessario mostrare come si presenta l'oggetto 'Thread'. – RPM1984
Così ho provato a rimuovere il controllo dello stato del modello e vedere se funzionasse. Ora ottengo questo errore: "Un oggetto entità non può essere referenziato da più istanze di IEntityChangeTracker." –
beh ora stai parlando di Entity Framework. Devi fornire maggiori informazioni. Cosa fa '_repository.AddComment (thread, commenta)'? Sembra che tutto quello che dovresti fare è recuperare il thread esistente tramite ThreadId, quindi fare 'thread.Comments.Add (newComment); 'quindi salvare il thread. dovrebbe essere così. – RPM1984