I’m aware it’s a quite simple question but I’m a newbie to C#, ASP.NET MVC3 and ADO.Net Entity Framework and my friend google didn’t help me much…
So, I have two entities : Post and Comments, with a 1-n relation between them.
I would like to post a comment on a post in a simple form with a route giving the post’s id.
The GET part (id being the post’s id)
//
// GET: /Blog/Comment/5
public ActionResult Comment(int id)
{
Comment comment = new Comment();
comment.PostReference.EntityKey = new EntityKey("BlogEntities.Posts", "id", id);
return View(comment);
}
The POST Part :
//
// POST: /Blog/Comment/5
[HttpPost]
public ActionResult Comment(Comment comment)
{
if (ModelState.IsValid)
{
db.Comments.AddObject(comment);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
I took a ride in debugging mode, and it appears the key is set to null when the form is submitted.
If I set the postreference in the HttpPost method, it just works fine, but I don’t have any clue about the id at this point.
So, i think it must be set in the GET part…
Or maybe I’m totally going in the wrong direction ?
Thanks for any help.
As said before, totally stupid question…
Putting the id in method’s arg, and then setting the reference after the AddObject did the trick…
Hope it’ll help some lost birds like me…